Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

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 |
---------------------------------------
like image 616
user2694306 Avatar asked Sep 08 '15 13:09

user2694306


1 Answers

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;
like image 153
Strawberry Avatar answered Sep 18 '22 22:09

Strawberry