我有一个带有computerid,userid和其他几列的MySQL表。现在我想要一个查询,它将返回多个用户共享computerid值的所有记录。查找以下示例数据:
computerid userid 100 5 105 10 110 6 100 7 101 11 100 5 105 10 101 11
对于上面的数据集,mysql查询应返回以下结果,因为在这种情况下,computerid由两个用户ID共享。
computerid userid 100 5 100 7
答案 0 :(得分:5)
你可以这样做:
SELECT DISTINCT T2.computerid, T2.userid
FROM (
SELECT computerid
FROM table1
GROUP BY computerid
HAVING COUNT(DISTINCT userid) > 1
) T1
JOIN table1 T2
ON T1.computerid = T2.computerid
结果:
computerid userid 100 5 100 7
在(computerid)上添加索引以提高性能。
答案 1 :(得分:1)
SELECT DISTINCT(computerid) , userid FROM table
WHERE computerid IN
(SELECT DISTINCT(computerid) FROM table GROUP BY computerid HAVING COUNT(computerid)>1)
答案 2 :(得分:0)
SELECT DISTINCT a.computerid, a.userId
FROM table a
JOIN (
SELECT computerId
FROM table
GROUP BY computerId
HAVING COUNT(DISTINCT userId) > 1
) b ON a.computerId = b.computerId
答案 3 :(得分:0)
没有子查询的解决方案
SELECT
t1.*
FROM table t1
LEFT JOIN table t2
ON t1.computerid = t2.computerid AND t1.userid != t2.userid
WHERE
t2.userid IS NOT NULL
GROUP BY
t1.computerid, t1.userid;
假设有少数计算机拥有多个用户,这应该相对较快。