MySQL在两列上选择唯一记录

时间:2014-12-16 00:59:43

标签: mysql sql

如何选择两列唯一的行?

给出表

id    col1   col2
1     a      222
2     b      223
3     c      224
4     d      224
5     b      225
6     e      226

如何删除col1中的重复项和col2中的重复项,以获取整个表的唯一行, 所以结果是

id   col1   col2
1    a      222
6    e      226

有没有比使用子查询更好的方法?

SELECT * FROM table WHERE id 
  IN (SELECT id FROM table WHERE col1 
        IN (SELECT col1 FROM table GROUP BY col1 HAVING(COUNT(col1)=1))
        GROUP BY col2 HAVING(COUNT(col2)=1))

2 个答案:

答案 0 :(得分:1)

这应该可以使用exists

select *
from yourtable y
where not exists (
  select 1
  from yourtable y2
  where y.id != y2.id
    and (y.col1 = y2.col1 
    or y.col2 = y2.col2))

这是使用outer join的替代解决方案,因为我读过mysql有时与exists不相符:

select *
from yourtable y
  left join yourtable y2 on y.id != y2.id
    and (y.col1 = y2.col1 
    or y.col2 = y2.col2)
where y2.id is null;

答案 1 :(得分:1)

您还可以通过聚合每个维度来实现此目的:

select t.*
from table t join
     (select col1
      from table t
      group by col1
      having count(*) = 1
     ) t1
     on t.col1 = t1.col1 join
     (select col2
      from table t
      group by col2
      having count(*) = 1
     ) t2
     on t.col2 = t2.col2;

这种方法似乎是用户要求的直接翻译。

相关问题