MySQL:Group按多个字段和计数

时间:2014-09-11 11:28:25

标签: mysql

此类问题在“MySQL: Group By & Count Multiple Fields

后发表

编辑:使用了示例查询

SELECT actors.id AS actor_id,actors.act_name AS actor_name,details.registration_id AS
 注册游戏INNER JOIN演员ON actors.id = games.actor_id INNER JOIN
详情ON details.id = games.detail_id WHERE'cond'GROUP BY注册,actor_id;

但是,在我的情况下,我无法实现它。我的表数据差别不大(我通过注册将表分组为actor_id)。例如:

actor_id | actor_name     | registration
----------------------------------------
189      | ABC            | 1234-1234
189      | ABC            | 4567-1234
189      | ABC            | 7890-4321
169      | DEF            | 1111-5643
169      | DEF            | 1111-5643

我希望输出如下

actor_id | actor_name     | registration | actor_count
------------------------------------------------------
189      | ABC            | 1234-1234    | 3
189      | ABC            | 4567-1234    | 3
189      | ABC            | 7890-4321    | 3
169      | DEF            | 1111-5643    | 2
169      | DEF            | 1111-5643    | 2

那是演员ABC在表中有3次出现而DEF有2次出现等等 相反,当我使用count(*)时,每行的预期计数为1 但是,有没有办法实现上述输出?

3 个答案:

答案 0 :(得分:0)

您可以通过对同一个表执行子查询来实现此目的。也许是这样的:

SELECT
    actors.actor_id,
    actors.actor_name,
    actors.registration,
    (
        SELECT
            COUNT(*)
        FROM
            actors AS innerActors
        WHERE innerActors.actor_id=innerActors.actor_id
    ) AS actor_count
FROM
    actors

答案 1 :(得分:0)

您可以通过将基表连接到聚合子查询(在mysql中)来实现目标。

例如:

SELECT
  A.actor_id, A.actor_name, A.registration, B.actor_count
FROM
  YourTable AS A
  INNER JOIN (
    SELECT
      actor_id, COUNT(1) AS actor_count
    FROM
      YourTable
    GROUP BY
      actor_id
  ) B
    ON A.actor_id = B.actor_id

答案 2 :(得分:0)

编写一个子查询,获取每个actor的计数。然后将其与原始表连接,将计数放在每个行上。

SELECT t1.actor_id, t1.actor_name, t1.registration, t2.actor_count
FROM YourTable AS t1
JOIN (SELECT actor_id, COUNT(*) AS actor_count
      FROM YourTable
      GROUP BY actor_id) AS t2 ON t1.actor_id = t2.actor_id

DEMO

如果您在分组中加入registration,那么您将获得1的计数,因为每行的注册都不同。