如何删除Table2中的行,表2中的WHERE的COUNT大于0?

时间:2016-11-25 09:35:50

标签: mysql sql count left-join

我的[Table1]具有用户ID,[Table2]具有相同的用户ID(左连接)和列“打开”,具有已读消息的数量。我想从[Table1]中删除所有用户,这些用户的[Table2]中的所有行都带有“open”列值< 1.我首先尝试选择它们,但它会产生SQL错误:

尝试1:

SELECT pg_acymailing_subscriber.*,
       COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 end) as readc
LEFT JOIN `pg_acymailing_userstats`
    ON pg_acymailing_subscriber.subid=pg_acymailing_userstats.subid
WHERE pg_acymailing_subscriber.subid=24 AND readc > 0;

尝试2:

SELECT *
FROM `pg_acymailing_subscriber`
LEFT JOIN `pg_acymailing_userstats`
    ON pg_acymailing_subscriber.subid=pg_acymailing_userstats.subid
WHERE COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 /*If user doesn't have rows with "open" column value > 0, we select it if whole rows numer is 0*/
                     end) < 1
  and pg_acymailing_subscriber.subid=24;

3 个答案:

答案 0 :(得分:1)

如果性能不是问题,那么使用子查询构建它可能是最容易的。

我对你的逻辑的理解是你要删除[Table1]中[Table2]中open > 0中没有任何行的所有用户,这是对你的要求的正确解释吗?

select * from pg_acymailing_subscriber where subid not in
( select subid from pg_acymailing_userstats where open > 0 )

如果显示正确的记录,请删除如下:

delete from pg_acymailing_subscriber where subid not in
( select subid from pg_acymailing_userstats where open > 0 )

答案 1 :(得分:1)

如果要过滤聚合函数的结果,则需要GROUP BY和HAVING子句,例如

SELECT pg_acymailing_subscriber.userid,
       COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 end) as readc
FROM `pg_acymailing_subscriber`
LEFT JOIN `pg_acymailing_userstats`
    ON pg_acymailing_subscriber.subid=pg_acymailing_userstats.subid
WHERE pg_acymailing_subscriber.subid=24
GROUP BY pg_acymailing_subscriber.userid
HAVING readc > 0;

我猜测用户ID列名为userid。我可能没有正确的引用,但这很容易修复。

HAVING readc > 0可能是也可能不是mysql中的正确语法。 如果不是,请编写HAVING COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 end) > 0

答案 2 :(得分:1)

如果我正确理解你想要删除table1中与table2中的id相关的行,那么所有打开消息的总和是&lt; 1
这应该是选择

  select table1.userID
  from table1 
  inner  join table2 on table1.userID = table2.userID 
  group by table1.userID
  havine sum(open)<1

然后您可以使用删除

  detele 
  from table1 
  inner  join table2 on table1.userID = table2.userID 
  group by table1.userID
  havine sum(open)<1