子查询中WHERE子句中的未知列

时间:2017-07-06 11:11:02

标签: mysql sql-server

我有页面表,我试图截断。 我需要保留每个页面的最后10个版本(页面由uid标识。)

id----|----uid----|----version

1 ----|---- 1 ----|---- 1

2 ----|---- 1 ----|---- 2

3 ----|---- 1 ----|---- 3

4 ----|---- 1 ----|---- 4

5 ----|---- 2 ----|---- 1

6 ----|---- 2 ----|---- 2

...........

55 ----|---- 1 ----|---- 23

56 ----|---- 2 ----|---- 14

57 ----|---- 2 ----|---- 15

我尝试过这个MySQL查询:

DELETE FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10) 
    AS Versions
)

但是在SQL之上返回:

  

'where子句'中的未知列'p.uid'

On Stackoverflow是像我一样的类似问题的答案,但由于我不是SQL忍者,我无法转换任何这些以适应我的问题。 我也不想过度使用我的查询。 必须有一些简单的答案。

我可以使用下面的查询在MSSQL Server中实现所需的截断:

DELETE FROM pages WHERE id NOT IN (
    SELECT Versions.id FROM
        (SELECT TOP (10) q.id FROM pages AS q WHERE pages.uid = q.uid ORDER BY q.version DESC) 
    AS Versions
)

由于

3 个答案:

答案 0 :(得分:1)

您不需要在此处协调查询;只需选择要删除的ID列表 - 表格是相同的

DELETE FROM pages WHERE id NOT IN 

    (SELECT TOP (10) id FROM pages ORDER BY q.version DESC) 

你不能按照"顺序排列。删除查询..

如果您使用的是MySQL版本,并且您的MySQL版本不支持子查询的LIMIT,并且它不支持这样的窗口函数:

delete from pages where id in 
  (select id from 
    (select id, row_number() over(order by dt desc) as rown from pages) a where a.rown > 10) 
  ) 

然后你可以考虑这样的事情:

CREATE table x as SELECT * FROM pages ORDER BY q.Version DESC LIMIT 10

TRUNCATE /*or delete from*/ pages

INSERT INTO pages SELECT * FROM x

答案 1 :(得分:1)

DELETE PG FROM pages PG
LEFT JOIN 
 (
    SELECT  q.id FROM pages AS q ORDER BY q.version DESC LIMIT 10 OFFSET 0
 ) Versions ON Versions.ID=PG.ID
WHERE Versions.ID IS NULL

您可以尝试以上查询。

希望这会对你有所帮助。

答案 2 :(得分:0)

DELETE p FROM pages AS p WHERE p.id IN (
    SELECT Versions.id FROM
        (SELECT q.id FROM pages AS q WHERE p.uid = q.uid ORDER BY q.version DESC LIMIT 10) 
    AS Versions
)

检查这是否有效..