[英]How to check if records with same foreign key have certain values
See below table: 见下表:
id foreign_key_id event_type event_status
---------------------------------------
1 1 20 1
2 1 20 2
3 1 30 1
4 1 30 2
5 2 20 1
6 2 20 2
7 2 30 1
Basically, I want to a query to return only foreign keys which have a record with event type 20 with status 1 but don't have a record with event type 30 and status 2 基本上,我想查询只返回具有事件类型为20且状态为1的记录但没有事件类型为30和状态2的记录的外键
In this scenario it should return the fk 2. 在这种情况下,它应该返回fk 2。
You can use a correlated subquery. 您可以使用相关子查询。
SELECT DISTINCT foreign_key_id
FROM yourTable AS t1
WHERE t1.event_type = 20 and t1.event_status = 1
AND foreign_key_id NOT IN (
SELECT foreign_key_id
FROM yourTable AS t2
WHERE t1.foreign_key_id = t2.foreign_key_id
AND t2.event_type = 30 AND t2.event_status = 2)
It can also be done with a LEFT JOIN
: 也可以通过
LEFT JOIN
来完成:
SELECT DISTINCT t1.foreign_key_id
FROM yourTable AS t1
LEFT JOIN yourTable AS t2
ON t1.foreign_key_id = t2.foreign_key_id
AND t2.event_type = 30 AND t2.event_status = 2
WHERE t1.event_type = 20 and t1.event_status = 1
AND t2.id IS NULL
select distinct foreign_key_id
from tablename
where event_type = 20
and event_status = 1
and foreign_key_id not in (
select distinct foreign_key_id
from tablename
where event_type = 30
and event_status = 2
);
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.