我的数据库包含通常如下所示的行:
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 ║
╚════╩══════════╩════════╝
我需要找到所有实际记录,其中PersonId和ItemId列匹配数据库中这两列的其他记录....
| 1 | 123 | 456
| 2 | 123 | 456
| 5 | 123 | 456
| 4 | 444 | 456
| 7 | 444 | 456
如何获得这些结果?
答案 0 :(得分:7)
您可以使用联接来处理重复记录。
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
输出
╔════╦══════════╦════════╗
║ ID ║ PERSONID ║ ITEMID ║
╠════╬══════════╬════════╣
║ 1 ║ 123 ║ 456 ║
║ 2 ║ 123 ║ 456 ║
║ 5 ║ 123 ║ 456 ║
║ 4 ║ 444 ║ 456 ║
║ 7 ║ 444 ║ 456 ║
╚════╩══════════╩════════╝
答案 1 :(得分:4)
这样的事情可以解决问题:
SELECT P1.*
FROM PersonItem P1
INNER JOIN PersonItem P2 ON P2.ID <> P1.ID
AND P2.PersonId = P1.PersonId
AND P2.ItemId = P1.ItemId
答案 2 :(得分:3)
您需要找到一对personid / itemid出现不止一次的示例。在MySQL中,您可以使用where
子句和子查询来执行此操作:
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
)
以上是标准SQL。 MySQL还支持多列in
语句。所以这可以写成:
select t.*
from t
where (t.personid, t.itemid) in (select personid, itemid
from t
group by personid, itemid
having count(*) > 1
)
根据Eugene的回答,我更喜欢的替代方案是:
SELECT t.personid, t.ItemId, GROUP_CONCAT(t.ID)
FROM t
GROUP BY t.personid, t.ItemId
HAVING COUNT(*) > 1;
如果您不介意将ID作为列表而不是单独的行,它会消除任何连接。
答案 3 :(得分:3)
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