【问题标题】:MYSQL Delete Query based on condtionMYSQL 根据条件删除查询
【发布时间】:2021-07-16 23:20:05
【问题描述】:

我有一个表 Product,我还有另一个表 Rating 我想删除 3 个或更多评分低于 3 的产品。

这是我尝试过的

DELETE p  FROM product p 
JOIN rating r ON r.produits_id = p.id  
IN
  (SELECT produits_id 
  FROM rating 
WHERE rating.score < 3
GROUP BY rating.produits_id  
HAVING COUNT(*)  > 2 )

【问题讨论】:

    标签: mysql sql join count sql-delete


    【解决方案1】:

    您应该将表直接连接到返回来自rating 的 id 的查询:

    DELETE p  
    FROM product p 
    JOIN (
      SELECT produits_id 
      FROM rating 
      WHERE score < 3
      GROUP BY produits_id  
      HAVING COUNT(*)  > 2
    ) r ON r.produits_id = p.id  
    

    【讨论】:

    • 收到此错误:无法删除或更新父行:外键约束失败
    • @AbdelmlakDhif 您已在表 rating 中将 produits_id 定义为产品 id 的外键,因此您无法删除在 produits_id 列中的 rating 中存在 id 的产品。您应该使用 ON DELETE CASCADE 定义 produits_id,以便在删除产品时,表 rating 中具有该 id 的所有行也将被删除。
    • yesssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss谢谢你接受你的回答!
    【解决方案2】:

    您可以在where 子句中使用in

    DELETE p 
        FROM product p 
        WHERE p.id  IN (SELECT r.produits_id 
                        FROM rating r
                        WHERE r.score < 3
                        GROUP BY r.produits_id  
                        HAVING COUNT(*)  >= 3
                       );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      相关资源
      最近更新 更多