我有一个项目表和另一份报告。每个报告都有一个外键链接到正在报告的项目。
我正在尝试删除此查询中显示的所有项目:
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
答案 0 :(得分: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)
答案 1 :(得分: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
项目别名。
答案 2 :(得分: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)
答案 3 :(得分: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
);