3

我有一个项目表和另一个报告。每个报告都有一个外键链接到正在报告的项目。

我正在尝试删除此查询中显示的所有项目:

SELECT items.id, title, SUM(weight) AS total_weight, SUM(weight)*10/views AS score 
FROM items, reports 
WHERE items.id = reports.item_id 
GROUP BY items.id 
HAVING score >= 50;

尝试这样的事情:

DELETE items 
FROM (SELECT items.id, title, SUM(weight) AS total_weight, SUM(weight)*10/views AS score 
    FROM items, reports 
    WHERE items.id = reports.item_id 
    GROUP BY items.id 
    HAVING score >= 50)
AS T;

给我这个错误信息:

ERROR 1109 (42S02): Unknown table 'items' in MULTI DELETE
4

4 回答 4

4

在 MySQL 中,您必须小心子查询。我认为以下工作:

DELETE FROM items 
WHERE id IN (select *
             from (SELECT items.id 
                   FROM items join reports 
                        on items.id = reports.item_id 
                   GROUP BY items.id 
                   HAVING SUM(weight)*10/views >= 50
                  )
            )

它通过使用额外的子查询来欺骗编译器接受查询。我还修正了你的join语法。

但是,以下使用相关子查询将查询重写为更常见的语法:

delete from items
where exists (select r.item_id
              from reports r
              where r.item_id = items.item_id 
              group by r.item_id
              having SUM(r.weight)*10/items.views >= 50
             )

这是猜测,weight而是views来自reports. Otherwise, you need to put the前面的 items 别名。

于 2012-12-27T16:37:06.573 回答
4
DELETE FROM items 
WHERE 
  id IN (
    SELECT 
      items.id 
    FROM items, reports 
    WHERE items.id = reports.item_id 
    GROUP BY items.id 
    HAVING SUM(weight)*10/views >= 50)
于 2012-12-27T16:26:32.480 回答
2

我相信你的delete说法是错误的。应该是delete from tablename where [condition]

    DELETE FROM items 
    WHERE 
      id IN (
        Select T.id from (SELECT items.id, title, SUM(weight) AS total_weight, SUM(weight)*10/views AS score 
FROM items, reports 
WHERE items.id = reports.item_id 
GROUP BY items.id 
HAVING score >= 50) T)
于 2012-12-27T16:27:50.890 回答
1

尝试这个:

DELETE FROM items 
WHERE id IN (SELECT id 
             FROM (SELECT i.id itemId, (SUM(weight) * 10 / views) score
                   FROM items i INNER JOIN reports r ON i.id = r.item_id 
                   GROUP BY itemId HAVING score >= 50
                  ) AS A
            );
于 2012-12-27T16:40:28.587 回答