我有下表:ID1、ID2、姓名、性别
表中存在 ID1 重复但 ID2、姓名和性别不同的记录 -- 也存在 ID2 重复但 ID1、姓名和性别不同的记录。 ID1 和 ID2 都可以有空值,但同一条目不能有空值。 我需要为 id1 和 id2 选择不重复的记录,例如
id1 id2 name sex
10 null jack M
10 null tom M
null 40 jennie F
null 32 jenie F
null 32 emma M
10 null stevie M
需要选择查询才能返回:
id1 id2 name sex
10 any any any (any means it can be either jack,tom,stevie)
null 40 jennie F
null 32 any any2 (any2 meaning jeniw or emma)
最佳答案
您可以在 WHERE
子句中使用 EXISTS
:
select t1.id1,
t1.id2,
name,
sex
from yourtable t1
where exists (select *
from yourtable t2
where t1.id1 = t2.id1
or t1.id2 = t2.id2)
group by t1.id1, t1.id2
关于mysql - 选择不同的 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12150503/