我有一张 table :-
id, event_type
0, sent
1, sent
2, sent
3, sent
4, sent
2, delivered
4, delivered
现在,我想要所有那些id
,其中有sent
event_type,但没有delivered
,即0, 1 , 3,
我可以使用嵌套查询或 MINUS 查询来完成此操作:-
select id from table where event_type = 'sent'
MINUS
select id from table where event_type = 'delivered';
但这是两个不同的查询。如何仅通过 1 个查询即可完成此操作?
我知道有可能进行 JOIN 查询。是否也有可能不使用 JOIN 查询并仍然获得必要的输出?
最佳答案
您可以使用 HAVING
子句和 GROUP BY
进行基于条件聚合的过滤:
SELECT id
FROM your_table_name
/* consider only those id(s) which has either sent and/or delivered */
WHERE event_type IN ('sent', 'delivered')
GROUP BY id
HAVING SUM(event_type = 'sent') /*Consider id which has 'sent' */
AND NOT SUM(event_type = 'delivered') /*Ignore id which has 'delivered' */
<小时/>
另一个选项是使用 Correlated Subquery with NOT EXISTS
和DISTINCT
:
SELECT DISTINCT t1.id
FROM your_table_name AS t1
WHERE t1.event_type = 'sent'
AND NOT EXISTS (SELECT 1 FROM your_table_name AS t2
WHERE t2.id = t1.id AND
t2.event_type = 'delivered')
关于mysql - 没有 JOIN 的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57605835/