My database contains rows that generally look like:
PersonItem
__________
id
personId
itemId
╔════╦══════════╦════════╗
║ ID ║ PERSONID ║ ITEMID ║
╠════╬══════════╬════════╣
║ 1 ║ 123 ║ 456 ║
║ 2 ║ 123 ║ 456 ║
║ 3 ║ 123 ║ 555 ║
║ 4 ║ 444 ║ 456 ║
║ 5 ║ 123 ║ 456 ║
║ 6 ║ 333 ║ 555 ║
║ 7 ║ 444 ║ 456 ║
╚════╩══════════╩════════╝
I need to find all the actual records where the PersonId and the ItemId column match some other record in the database for those two columns....
| 1 | 123 | 456
| 2 | 123 | 456
| 5 | 123 | 456
| 4 | 444 | 456
| 7 | 444 | 456
How can I go about getting these results?
You can do joins to get around with duplicate records.
SELECT a.*
FROM TableName a
INNER JOIN
(
SELECT PersonID, ItemID, COUNT(*) totalCount
FROM TableName
GROUP BY PersonID, ItemID
HAVING COUNT(*) > 1
) b ON a.PersonID = b.PersonID AND
a.ItemID = b.ItemID
OUTPUT
╔════╦══════════╦════════╗
║ ID ║ PERSONID ║ ITEMID ║
╠════╬══════════╬════════╣
║ 1 ║ 123 ║ 456 ║
║ 2 ║ 123 ║ 456 ║
║ 5 ║ 123 ║ 456 ║
║ 4 ║ 444 ║ 456 ║
║ 7 ║ 444 ║ 456 ║
╚════╩══════════╩════════╝
Something like this should do the trick:
SELECT P1.*
FROM PersonItem P1
INNER JOIN PersonItem P2 ON P2.ID <> P1.ID
AND P2.PersonId = P1.PersonId
AND P2.ItemId = P1.ItemId
SELECT GROUP_CONCAT(p1.ID), p1.personid, p1.ItemId
FROM PersonItem AS p1
INNER JOIN PersonItem AS p2 ON
p1.ID<>p2.ID
AND p1.personid=p2.personid
AND p1.ItemId=p2.ItemId
GROUP BY p1.personid, p1.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With