mysql - 没有 JOIN 的 SQL 查询

标签 mysql sql

我有一张 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 EXISTSDISTINCT:

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/

相关文章:

mysql - 获取每个连接列的有限行数

php - 在双引号或单引号中打印 HTML 和 PHP 代码

java - 在 android studio 中尝试从我的数据库中打印数据后,我得到一个空引用异常

mysql - SQL查询检索所有教授

mysql - 从具有 b=a +"s"的表中选择 col1 作为 a,col1 作为 b ?

php - 在排名搜索查询中指定排名 PHP、MySQL

php - Doctrine2 首先查询具有特定值的 orderBy

mysql - Elasticsearch SQL 等效项

mysql - 在同一列上连接同一个表两次,不同的值仅返回最近的行

sql - SQL*Plus 中的清除屏幕