MySQL SELECT FROM WHERE COUNT

时间:2014-06-04 14:36:22

标签: php mysql sql count where

我正在寻找一个只返回列xxx

中带有加倍条目的行的MySQL Select

示例:

+------+------+------------+--------------------+
| id   | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|    1 | John | 2007-01-24 |                250 |
|    2 | Ram  | 2007-05-27 |                220 |
|    3 | Jack | 2007-05-06 |                170 |
|    4 | Jack | 2007-04-06 |                100 |
|    5 | Jill | 2007-04-06 |                220 |
|    6 | Zara | 2007-06-06 |                300 |
|    7 | Zara | 2007-02-06 |                350 |
+------+------+------------+--------------------+

获得此表,我想读出名称列出多次的所有条目, 我的查询无效,因为它只显示两次名称的条目

SELECT id, name, COUNT(name) AS count
    FROM table_xy   
    having count(name) > 1;

我想要归还的内容:

+------+------+------------+
| id   | name |   count    | 
+------+------+------------+
|    3 | Jack |     2      |
|    4 | Jack |     2      |
|    6 | Zara |     2      |
|    7 | Zara |     2      |
+------+------+------------+

有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式为您的论坛使用子查询:

SELECT  x.id, y.name, y.count
FROM    table_xy AS x
        INNER JOIN
        (   SELECT  Name, COUNT(*) AS count
            FROM     table_xy
            GROUP BY Name
            HAVING COUNT(*) > 1
        ) AS y
            ON y.Name = x.Name;

或者,如果您不需要计数,则可以使用不同的自联接:

SELECT  DISTINCT x.ID, x.Name
FROM    table_xy AS x
        INNER JOIN table_xy AS y
            ON x.Name = y.Name
            AND x.ID != y.ID;

如果您确实需要计数,可以自行加入GROUP BY:

SELECT  x.ID, x.Name, COUNT(y.ID) + 1 AS count
FROM    table_xy AS x
        INNER JOIN table_xy AS y
            ON x.Name = y.Name
            AND x.ID != y.ID
GROUP BY x.ID, x.Name;

<强> Examples on SQL Fiddle

答案 1 :(得分:0)

试试这个......

SELECT  x.ID, x.Name, COUNT(y.ID) + 1 AS count

FROM table_xy AS x

INNER JOIN table_xy AS y

ON x.Name = y.Name

AND x.ID!= y.ID GROUP BY x.ID,x.Name;