SQL - select rows that have the same value in two columns

You can use exists for this:

select * 
from yourtable y
where exists (
  select 1
  from yourtable y2 
  where y.name <> y2.name
    and y.cardnumber = y2.cardnumber
    and y.membertype = y2.membertype)
  • SQL Fiddle Demo

Since you mentioned names can be duplicated, and that a duplicate name still means is a different person and should show up in the result set, we need to use a GROUP BY HAVING COUNT(*) > 1 in order to truly detect dupes. Then join this back to the main table to get your full result list.

Also since from your comments, it sounds like you are wrapping this into a view, you'll need to separate out the subquery.

CREATE VIEW DUP_CARDS
AS
SELECT CARDNUMBER, MEMBERTYPE
FROM mytable t2
GROUP BY CARDNUMBER, MEMBERTYPE
HAVING COUNT(*) > 1

CREATE VIEW DUP_ROWS
AS
SELECT t1.*
FROM mytable AS t1
INNER JOIN DUP_CARDS AS DUP
ON (T1.CARDNUMBER = DUP.CARDNUMBER AND T1.MEMBERTYPE = DUP.MEMBERTYPE )

SQL Fiddle Example


What's the most efficient way of doing this?

I believe a JOIN will be more efficient than EXISTS

SELECT t1.* FROM myTable t1
JOIN (
    SELECT cardnumber, membertype
    FROM myTable
    GROUP BY cardnumber, membertype
    HAVING COUNT(*) > 1
) t2 ON t1.cardnumber = t2.cardnumber AND t1.membertype = t2.membertype

Query plan: http://www.sqlfiddle.com/#!2/0abe3/1

Tags:

Mysql

Sql

Join