5

我的数据库包含通常看起来像这样的行:

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

我怎样才能得到这些结果?

4

4 回答 4

8

您可以进行连接以解决重复记录。

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 ║
╚════╩══════════╩════════╝
于 2013-05-29T00:29:49.430 回答
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
于 2013-05-29T00:31:27.507 回答
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
于 2013-05-29T00:31:42.887 回答
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
                                )

我喜欢的替代方案,基于尤金的回答,但更有效,是:

SELECT t.personid, t.ItemId, GROUP_CONCAT(t.ID)
FROM t
GROUP BY t.personid, t.ItemId
HAVING COUNT(*) > 1;

如果您不介意将 id 作为列表而不是单独的行,它会取消任何连接。

于 2013-05-29T00:28:59.417 回答