如果计数超过10,则删除子记录

时间:2018-04-06 08:14:58

标签: mysql

我有以下表格的父子关系:

CREATE TABLE `pages` (
    id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(100) NULL,
    PRIMARY KEY ( id )
)

CREATE TABLE `pageObjects` (
    id INT NOT NULL AUTO_INCREMENT,
    object TEXT NULL,
    lastChanged TIMESTAMP on update CURRENT_TIMESTAMP NOT NULL,
    fkPageId int NOT NULL,
    PRIMARY KEY ( id )
)

pagespageObjects有一个很多关系。

每当连接到单个页面的pageObjects条记录超过10条时,必须删除过去编辑得最远且超过10条的所有记录。

我想在一个查询中执行此操作,但我似乎无法弄明白...

这是我走了多远:

DELETE 
FROM pageObjects
WHERE id NOT IN (
    SELECT po.id, po.fkPageId FROM (
        SELECT objects.fkPageId FROM (
            SELECT COUNT(*) as count, fkPageId
            FROM pageObjects
            GROUP BY fkPageId
        ) objects
        WHERE count > 10
    ) AS page
    JOIN pageObjects po 
    ON page.fkPageId = po.fkPageId
    AND po.lastChanged  < (
        SELECT MIN(lastChanged )
        FROM pageObjects
        WHERE fkPageId = po.fkPageId
        GROUP BY fkPageId
        ORDER BY lastChanged  DESC
        LIMIT 10
    )
)

可悲的是,底部子查询中的LIMIT位没有按照我想要的方式工作,因为MIN()函数应该在应用LIMIT之后应用。

所以我试过了:

DELETE 
FROM pageObjects
WHERE id NOT IN (
    SELECT po.id, po.fkPageId FROM (
        SELECT objects.fkPageId FROM (
            SELECT COUNT(*) as count, fkPageId
            FROM pageObjects
            GROUP BY fkPageId
        ) objects
        WHERE count > 10
    ) AS page
    JOIN pageObjects po 
    ON page.fkPageId = po.fkPageId
    AND po.lastChanged  < (
        SELECT MIN(lastChanged)
        FROM (  
            SELECT lastChanged
            FROM pageObjects
            WHERE fkPageId = po.fkPageId
            GROUP BY fkPageId
            ORDER BY lastChanged DESC
            LIMIT 10
        )
    )
)

但这是不可能的,因为po.fkPageId在子查询的子查询中不可用。

有没有办法像这样做?

1 个答案:

答案 0 :(得分:1)

您可以通过计算每个ID的后续条目数量来完成此操作:

DELETE FROM pageObjects
WHERE id IN (
  SELECT id FROM pageObjects po
  WHERE (
    SELECT count(id) 
    FROM pageObjects po2 
    WHERE po2.fkPageId = po.fkPageId
    AND po2.lastChanged > po.lastChanged
  ) > 10
)

查看select返回的内容: http://www.sqlfiddle.com/#!9/f5218f/1/0