mysql - 如何检查具有相同外键的记录是否具有特定值

标签 mysql

见下表:

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

基本上,我想查询仅返回具有事件类型 20 和状态 1 的记录但没有事件类型 30 和状态 2 的记录的外键

在这种情况下,它应该返回 fk 2。

最佳答案

您可以使用相关子查询。

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

它也可以通过 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

关于mysql - 如何检查具有相同外键的记录是否具有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102483/

相关文章:

MySQL - 需要找到 SUM 查询的最大值

mysql - fedora linux环境,mysql中select失败

mysql - 重复 SQL select 语句直到满足条件

php - 获取二维数组中的数据

mysql - 如何在cakephp find()方法中编写mysql AND/OR

php - 为什么我的内连接查询不起作用

mysql - 如何提取 10 分钟间隔内记录在 mysql 慢查询日志中的查询数量(计数)

mysql - 编写 MySQL 查询的新手

php - 如何在php中传递blob作为参数并将其上传到MySQL数据库?

c++ - 将 mysqlx::Value 转换为带有特殊字符的 std::string