MySQL - 在WHERE子句中使用COUNT(*)?

时间:2011-10-09 14:17:51

标签: mysql

好的,所以我想找到所有具有相同值的行。(或至少一对)

James| 19.193.283.19
John| 20.134.232.344
Jack| 19.193.283.19 
Jonny| 19.193.283.19

我希望它能返回詹姆斯,杰克和强尼的行 - 其中不止一行有IP '19 .193.283.19'。

我试着做其他类似问题的回答:

select *
from `Zombie`
group by `Ip`
having count(*) > 1
order by `Ip` desc

但它只返回了一行,其中一对或更多类似的'Ip'我想要每一行。

如何修改SQL以便返回所有独立的行?

非常感谢。

2 个答案:

答案 0 :(得分:5)

您可以使用exists子查询查找具有相同Ip匹配行的所有行:

select  *
from    YourTable as yt1
where   exists
        (
        select  *
        from    YourTable as yt2
        where   yt1.name <> yt2.name
                and yt1.Ip = yt2.Ip
        )

使用相同Ip的行数进行排序可以通过自联接来完成,例如:

select  yt1.name
,       yt1.Ip
from    YourTable as yt1
join    YourTable as yt2
on      yt1.name <> yt2.name
        and yt1.Ip = yt2.Ip
group by
        yt1.name
,       yt1.Ip
order by
        count(yt2.name) desc

答案 1 :(得分:0)

另一种方法是将表与您已经使用过的子查询联系起来(找到存在于多行中的ips):

SELECT t.name
     , t.Ip
FROM 
    YourTable AS t
  JOIN
      ( SELECT Ip
             , COUNT(*) AS cnt
        FROM YourTable
        GROUP BY Ip
        HAVING COUNT(*) > 1
      ) AS td
    ON td.Ip = t.Ip
ORDER BY
       td.cnt DESC
     , t.Ip
     , t.name