My database contains rows that generally look like:
PersonItem
__________
id
personId
itemId
╔════╦══════════╦════════╗
║ ID ║ PERSONID ║ ITEMID ║
╠════╬═══
You need to find examples where the pair of personid/itemid appear more than once. In MySQL you can do this with a where
clause and subquery:
select t.*
from t
where exists (select 1
from t t2
group by personid, itemid
having count(*) > 1 and
t2.personid = t.personid and t2.itemid = t.itemid
)
The above is standard SQL. MySQL also supports the multi-column in
statement. So this can be written as:
select t.*
from t
where (t.personid, t.itemid) in (select personid, itemid
from t
group by personid, itemid
having count(*) > 1
)
And alternative that I like, based on Eugene's answer but more efficient, is:
SELECT t.personid, t.ItemId, GROUP_CONCAT(t.ID)
FROM t
GROUP BY t.personid, t.ItemId
HAVING COUNT(*) > 1;
It does away with any joins, if you don't mind getting the ids as a list rather than as separate rows.