如何从表中找到大多数重复元素?

时间:2011-07-26 09:36:23

标签: mysql

我有一个表tbl_user,我想找到哪个user_name(s)表中的重复值最多。我只想检索那些user_id(s)。

我还需要一个单独的查询来查找表中重复user_name(s)的计数。

5 个答案:

答案 0 :(得分:1)

查找重复用户名最多的第一个查询:

  SELECT user_name, COUNT(user_id) AS amount
    FROM tbl_user
GROUP BY user_name
ORDER BY amount DESC

然后抓住id:

# faster way using username from last query

  SELECT user_id
    FROM tbl_user
   WHERE user_name = '$user_name'


# longer way

  SELECT user_id
    FROM tbl_user
   WHERE user_name = (
       SELECT user_name
         FROM tbl_user
     GROUP BY user_name
     ORDER BY COUNT(amount) DESC
        LIMIT 1
   )

答案 1 :(得分:0)

要查找重复次数:

SELECT count(id) AS num_duplicates FROM tbl_users GROUP BY user_name ORDER BY num_duplicates DESC

查找最重复的user_name的user_id:

SELECT user_id FROM tbl_user 
    WHERE username IN ( SELECT user_id 
                           FROM tbl_users 
                        GROUP BY user_name 
                        ORDER BY count(id) DESC LIMIT 0, 1)

答案 2 :(得分:0)

SELECT COUNT(*) FROM tbl_user
GROUP BY tbl_user.user_name

将为您提供重复user_name的数量。如果您愿意,可以使用脚本语言选择最高的语言,或者如果您不需要自动化,则只需查看列表。

答案 3 :(得分:0)

如果您的意思是想要计算特定用户名的出现次数,则此类内容可能对您有用。

select user_name,user_id,count(*) as mycount from tbl_user group by user_name order by mycount desc limit 5

这应该得到前5个条目

答案 4 :(得分:0)

您可以选择与此SQL重复的user_name

SELECT COUNT(1) AS duplicates, user_name
FROM tbl_user
GROUP BY user_name
HAVING duplicates > 1

完成此操作后,您可以将其用作子查询来查找重复user_name的计数

SELECT COUNT(1) AS count_of_user_names, SUM(duplicates) AS duplicate_records
FROM (
  SELECT COUNT(1) AS duplicates, user_name
  FROM tbl_user
  GROUP BY user_name
  HAVING duplicates > 1
) AS subquery

或者用它来找出用户ID:

SELECT user_id
FROM tbl_user
WHERE user_name IN (
  SELECT user_name
  FROM tbl_user
  GROUP BY user_name
  HAVING COUNT(1) > 1
)