mysql - 查找源id只有一个dest id的行

标签 mysql sql

transferHistory 表:

╔════════════╦════════╗
║ sourceId   ║ destId ║
╠════════════╬════════╣
║       221  ║ 1      ║
║      2223  ║ 1      ║
║      2223  ║ 2      ║
║        44  ║ 3      ║
║        33  ║ 3      ║
║        55  ║ 3      ║
║        44  ║ 2      ║
╚════════════╩════════╝

所以我想查找 destId 是给定 id 并且给定 id 是源 id 的唯一目标 id 的所有行。

示例:

给定 dest id = 1,结果应为 221(因为源 2223 被分为两个目标 1 和 2)

给定 dest id = 2,结果应该为空(因为源 2223 和 44 都分为两个目的地)

给定 dest id = 3,结果应为 33 和 55。

如何编写 SQL 来获取它?

最佳答案

您只需要源 id,没有其他目标 id。这表明不存在:

select t.*
from t
where t.destId = @destId and
      not exists (select 1
                  from t t2
                  where t2.sourceId = t.sourceId and
                        t2.dest_id <> t.dest_id
                 );

如果您希望所有行都符合条件,则可以删除 t.destId = @destId

关于mysql - 查找源id只有一个dest id的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51977308/

相关文章:

php - 使用日期MySQL触发器自动删除数据

mysql - 在 Mac 上安装 MySQL 后如何运行

php - 使用php更新一次sql表字段

sql - 如何在 XP 中备份本地 SQL Server 数据库?

c# - 如何获取我当前插入到 Access 数据库中的东西的 ID

sql - 从表中选择不同 - 两列不应该有重复

sql - 查找组中第一行和剩余行之间的距离

java netbeans 新的驱动程序类是 `com.mysql.cj.jdbc.Driver'

php - 从我网站的另一部分获取 wordpress 特色图片 url

mysql - 如何设置评级表SQL