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/