[英]insert from table1 into table2 where time difference in value input on table 1 is greater than 5 minute
[英]How to delete rows in Table1 where COUNT of WHERE in Table2 is greater than 0?
我有具有用戶ID的[Table1]和具有相同用戶ID(左聯接)的[Table2],以及帶有已讀消息數的“開放”列。 我想從[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;
如果性能不是問題,那么使用子查詢來構建它可能是最簡單的。
我對您的邏輯的理解是,您想從[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 )
如果要過濾聚合函數的結果,則需要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列稱為用戶ID。 我的報價可能不正確,但是很容易修復。
而且HAVING readc > 0
可能是mysql中的正確語法,也可能不是。 如果不是,則編寫HAVING COUNT(DISTINCT case when pg_acymailing_userstats.open > 0 end) > 0
如果我正確理解您的問題,則要刪除表1中與表2中的ID相關的行,所有打開消息的總和<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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.