【问题标题】:how to Sql return only all duplicated entries如何Sql只返回所有重复的条目
【发布时间】:2009-08-11 09:43:39
【问题描述】:

我有一张桌子有

create table test(id int not null primary key, day date not null);

insert into test(id, day) values(1, '2006-10-08');
insert into test(id, day) values(2, '2006-10-08');
insert into test(id, day) values(3, '2006-10-09');

select * from test;
+----+------------+
| id | day        |
+----+------------+
|  1 | 2006-10-08 |
|  2 | 2006-10-08 |
|  3 | 2006-10-09 |
+----+------------+


select day, count(*) from test GROUP BY day;
+------------+----------+
| day        | count(*) |
+------------+----------+
| 2006-10-08 |        2 |
| 2006-10-09 |        1 |
+------------+----------+


select day, count(*) from test group by day HAVING count(*) > 1;
+------------+----------+
| day        | count(*) |
+------------+----------+
| 2006-10-08 |        2 |
+------------+----------+

我需要的是,我需要返回重复的条目

这是我需要的简单输出

+------------+----------+
| day        |    id    |
+------------+----------+
| 2006-10-08 |        2 |
| 2006-10-08 |        1 |
+------------+----------+

【问题讨论】:

    标签: sql mysql database


    【解决方案1】:

    尝试自加入

    SELECT T1.day, T1.id
    FROM   test T1
    INNER JOIN test T2
    ON T1.id <> T2.id AND T1.day = T2.day
    

    【讨论】:

      【解决方案2】:
      select id, count(day) as cnt from test group by day HAVING cnt > 1;
      

      【讨论】:

        猜你喜欢
        • 2010-11-18
        • 2012-05-13
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-23
        • 1970-01-01
        • 2020-11-02
        相关资源
        最近更新 更多