[英]Mysql query to find all rows that have the same values as another row
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.... 我需要找到所有实际记录,其中PersonId和ItemId列匹配数据库中这两列的其他记录....
| 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 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
You need to find examples where the pair of personid/itemid appear more than once. 您需要找到一对personid / itemid出现不止一次的示例。 In MySQL you can do this with a where
clause and subquery: 在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
)
The above is standard SQL. 以上是标准SQL。 MySQL also supports the multi-column in
statement. MySQL还支持多列in
声明。 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. 如果您不介意将ID作为列表而不是单独的行,它会消除任何连接。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.