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

join, mysql, sql

Solution

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

Problem

The solution to the topic is evading me. I have a table looking like (beyond other fields that have nothing to do with my question): NAME,CARDNUMBER,MEMBERTYPE Now, I want a view that shows rows where the cardnumber AND membertype is identical. Both of these fields are integers. Name is VARCHAR. Name is not unique, and duplicate cardnumber, membertype should show for the same name, as well. I.e. if the following was the table: ``` JOHN | 324 | 2 PETER | 642 | 1 MARK | 324 | 2 DIANNA | 753 | 2 SPIDERMAN | 642 | 1 JAMIE FOXX | 235 | 6 ``` I would want: ``` JOHN | 324 | 2 MARK | 324 | 2 PETER | 642 | 1 SPIDERMAN | 642 | 1 ``` this could just be sorted by cardnumber to make it useful to humans. What's the most efficient way of doing this?

Original source