首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有join、HAVING和GROUP BY的MySQL DELETE语句

带有join、HAVING和GROUP BY的MySQL DELETE语句
EN

Stack Overflow用户
提问于 2012-12-28 00:24:28
回答 4查看 5.6K关注 0票数 3

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

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

代码语言:javascript
运行
复制
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;

尝试像这样的东西:

代码语言:javascript
运行
复制
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;

显示以下错误消息:

代码语言:javascript
运行
复制
ERROR 1109 (42S02): Unknown table 'items' in MULTI DELETE
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-12-28 00:37:07

在MySQL中,您必须小心使用子查询。我认为下面的方法是可行的:

代码语言:javascript
运行
复制
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语法。

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

代码语言:javascript
运行
复制
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
             )

这是猜测weightviews来自前面的reports. Otherwise, you need to put the项的别名。

票数 4
EN

Stack Overflow用户

发布于 2012-12-28 00:26:32

代码语言:javascript
运行
复制
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)
票数 4
EN

Stack Overflow用户

发布于 2012-12-28 00:27:51

我相信您的delete语句是错误的。应该是delete from tablename where [condition]

代码语言:javascript
运行
复制
    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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14057791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档