【问题标题】:MySQL select unique records on two columnsMySQL在两列上选择唯一记录
【发布时间】:2019-07-10 13:20:22
【问题描述】:

如何选择两列唯一的行?

给定表格

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))

【问题讨论】:

    标签: mysql sql


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      您也可以通过沿每个维度聚合来做到这一点:

      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;
      

      这种方法似乎是对用户需求的一种非常直接的翻译。

      【讨论】:

        猜你喜欢
        • 2020-10-24
        • 2023-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 2012-12-21
        相关资源
        最近更新 更多