SQL - 选择共享公共值的行组

时间:2014-06-11 15:26:31

标签: mysql sql

我想要检索共享相同IP的帐户。

例如,给定以下登录表:

acc ip
1   a
2   b
3   a
4   c
5   d
6   e
1   f
4   b

我希望得到类似的内容:

acc ip
1   a
3   a
2   b
4   b

6 个答案:

答案 0 :(得分:3)

SELECT acc, ip
FROM YourTable
WHERE ip IN (SELECT ip
             FROM YourTable
             GROUP BY ip
             HAVING COUNT(*) > 1)
ORDER BY ip, acc

DEMO

答案 1 :(得分:2)

有很多方法可以做到这一点。这是一个简单的JOIN版本;

SELECT DISTINCT a.* 
FROM mytable a
JOIN mytable b
  ON a.ip = b.ip 
 AND a.acc<>b.acc
ORDER BY a.ip, a.acc;

An SQLfiddle to test with

它基本上将表连接到自己,以查找具有相同IP和另一个帐户的行。 DISTINCT用于使每个帐户/ IP组合仅显示一次。

答案 2 :(得分:0)

这样的事情?按字母顺序排列字母

SELECT acc, ip 
FROM table 
WHERE ip IN(    
    SELECT ip FROM table 
    GROUP BY ip HAVING count(ip) > 1
    ) ORDER BY ip, acc

答案 3 :(得分:0)

SELECT acc, ip
FROM tablename
WHERE ip IN (
    SELECT ip
    FROM tablename
    GROUP BY ip
    HAVING COUNT(acc) > 1)
ORDER BY ip ASC, acc ASC

答案 4 :(得分:0)

我觉得很难想到一个有用的场景,但就是这样:

SELECT acc, ip FROM table1 t
WHERE EXISTS (SELECT * FROM table1 WHERE ip = t.ip AND acc != t.acc);

答案 5 :(得分:0)

这是你正在寻找的吗?

SELECT acc, ip 
FROM mytable 
WHERE ip IN (SELECT ip FROM mytable GROUP BY ip HAVING COUNT(ip)>1)
ORDER BY ip, acc