繁体   English   中英

MySQL查询返回非唯一列组合

[英]MySQL query to return non unique column combination

我有一个带有计算机ID,用户ID和其他一些列的MySQL表。 现在,我需要一个查询,该查询将返回由多个用户共享computerid值的所有记录。 查找以下样本数据:

computerid  userid
100         5     
105         10    
110         6     
100         7     
101         11    
100         5     
105         10    
101         11

对于上述数据集,mysql查询应返回以下结果,因为在这种情况下,计算机标识由两个用户标识共享。

computerid  userid
100         5     
100         7

您可以这样做:

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)上添加索引以提高性能。

    SELECT DISTINCT(computerid) , userid FROM table  
WHERE computerid IN 
(SELECT DISTINCT(computerid)  FROM table GROUP BY computerid HAVING COUNT(computerid)>1)
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

没有子查询的解决方案

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;

假设很少有多于一个用户的计算机,这应该相对较快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM