简体   繁体   English

没有JOIN的SQL查询

[英]SQL query without a JOIN

I've a table:- 我有一张桌子:

id, event_type

0, sent
1, sent
2, sent
3, sent
4, sent
2, delivered
4, delivered

Now, I want all those ids in which there was a sent event_type, but not delivered , ie 0, 1, 3, 现在,我想要所有其中已sent event_type但未delivered ids ,例如0、1、3 0, 1, 3,

I can do it with a nested or a MINUS query:- 我可以用嵌套查询或减号查询来做到这一点:

select id from table where event_type = 'sent'
MINUS
select id from table where event_type = 'delivered';

But these are 2 different queries. 但这是2个不同的查询。 How can it be done in just 1 single query? 仅一个查询如何完成?

I know there's a possibility of a JOIN query. 我知道有可能进行JOIN查询。 Is there also a possibility without using a JOIN query and still getting the requisite output? 是否有可能不使用JOIN查询而仍然获得必要的输出?

You can do conditional aggregation based filtering using HAVING clause with GROUP BY : 您可以使用带有GROUP BY HAVING子句进行基于条件聚合的过滤:

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' */

Another Option is to use a Correlated Subquery with NOT EXISTS and DISTINCT : 另一个选择是使用带有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')

You should have done it via group by as you dont have multiple tables to refer columns and get values together neither you want to manipute column using self join to get another instance of your same table rather your requirement is to fetch resulTs of specific groups with some condition. 您应该通过分组方式完成操作,因为您没有多个表来引用列并将值汇总在一起,您也不想使用自连接来操纵列来获取同一表的另一个实例,而是您的要求是通过一些操作来获取特定组的结果条件。

  SELECT id, max(event_type) from table 
   group 
    by id 
   having count(distinct event_type)=1 
  and max(distinct event_type)='sent'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM