查找重复的帐户

时间:2014-05-09 17:23:55

标签: mysql sql

我有两张桌子,我想列出所有共享IP的帐户。例如,如果Id 1帐户和Id 2帐户的Session帐户IP相同。

帐户表:

Name: Account

Id   ... (more column names here)

会话表:

Id   Creator   Token   Expires   IP

到目前为止,我已经尝试了以下内容,但它并没有起到相应的作用。

SELECT `Account`.`Id`, `Account`.`Username`, `Session`.`IP` 
FROM `Session` 
  JOIN `Account` 
    ON `Account`.`Id` = `Session`.`Creator` 
WHERE `IP` != '' 
GROUP BY `Session`.`Creator`;

2 个答案:

答案 0 :(得分:1)

我猜您需要GROUP_CONCAT()

SELECT 
GROUP_CONCAT(`Account`.`Id`), 
GROUP_CONCAT(`Account`.`Username`),
 `Session`.`IP` 
FROM `Session` 
JOIN `Account` ON `Account`.`Id` = `Session`.`Creator`
 WHERE `IP` != ''
 GROUP BY `Session`.`Creator`
HAVING COUNT(*) > 1

这将为您提供逗号分隔的帐户ID列表,具有相同Creator的用户名

注意:要知道这个事实,它的默认限制为1024个字符,但它可以增加,这在手册中定义

答案 1 :(得分:0)

您找到具有多个帐户的IP

SELECT
   IP,
   COUNT (DISTINCT Creator) 
FROM
   `Sessions`
GROUP BY IP
HAVING COUNT(DISTINCT Creator) > 1

现在,您必须将此查询的结果加入您的帐户表:

SELECT
    a.Id,
    a.Username,
    s.IP
FROM
    Account a
INNER JOIN
    Session s
ON
    a.Id = s.Creator
WHERE s.IP IN (
    SELECT
       IP,
       COUNT (DISTINCT Creator) 
    FROM
       `Sessions`
    GROUP BY IP
    HAVING COUNT(DISTINCT Creator) > 1
)