简体   繁体   English

如何检查具有相同外键的记录是否具有某些值

[英]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)

DEMO 演示

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

DEMO 演示

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.

相关问题 过滤其他列中具有相同外键和不同值的记录 - Filter records with same foreign key and different values in other columns 在MySQL中,如何获取相同外键的所有值都显示在另一个列的列表中的记录 - In Mysql how to get records which for the same foreign key has all values showed up in a list for another col 如何检查外键对象是否为某种类型 - How can I check if the foreign key object is of a certain type Rails查看具有相同外键的所有记录 - Rails View All records with same foreign key 在尝试删除MySQL中的任何这些记录之前,如何检查记录列表的外键引用? - How can you check for foreign key references for a list of records before attempting to delete any of these records in MySQL? 3 不同的表具有相同的外键,如何选择 - 3 Different tables have same Foreign Key, How to select 如果它们具有相同的外键,如何将来自数据库的图像一起添加 - How to add images from a database together if they have the same foreign key 在两个记录中替换外键值(唯一) - Replacing foreign key values (unique) in two records mysql获取具有某些值的外部记录的记录 - mysql fetch records with foreign records having certain values 如何检查是否创建了外键 - How to check if a foreign key is created
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM