9

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

3 Answers 3

15

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Love it! Missed the disctinct at first and was thinking you get more rows, but nope, it's perfect :)
any idea how the performance of that is against the EXISTS solution? I can guess my sub-select solution would be the slowest
Love this old school style, making me think! :D
7

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.