简体   繁体   中英

MySQL - Select all rows where a field value is not unique

How can I select all rows in MySQL where a particular field value is not unique. For example I have the following data:

---------------------------------------
| ID | Name   |         URL           |
---------------------------------------
| 1  | Store 1| http://www.store1.com |
| 2  | Store 2| http://www.store1.com |
| 3  | Store 3| http://www.store3.com |
| 4  | Store 4| http://www.store4.com |
| 5  | Store 5| http://www.store4.com |
---------------------------------------

In this I would want to return the following where the URL field has duplicates:

---------------------------------------
| ID | Name   |         URL           |
---------------------------------------
| 1  | Store 1| http://www.store1.com |
| 2  | Store 2| http://www.store1.com |
| 4  | Store 4| http://www.store4.com |
| 5  | Store 5| http://www.store4.com |
---------------------------------------

or, old school...

SELECT DISTINCT x.* 
           FROM my_table x 
           JOIN my_table y 
             ON y.url = x.url 
            AND y.id <> x.id 
          ORDER 
             BY id;

If you want all the original rows, then use exists :

select t.*
from table t
where exists (select 1 from table t2 where t2.url = t.url and t2.id <> t.id);

You can inner join to your duplicates.

select t.* 
from table t
inner join
(select url from table group by 1 having count(*)>1) duplicates
on duplicates.url=t.url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM