根据另一个表id计算表行

时间:2014-04-18 07:16:55

标签: mysql select count

我正在尝试根据另一个表ID计算我的行

DRIVER DB TABLE

agent_id  driver_id   driver_name
--------  ----------  -----------
2         1           AAA
2         2           BBB
2         3           CCC
1         4           DDD

我想显示结果(根据agent_id有多少个驱动程序)。例如,agent_id 2有3个驱动程序agent_id 1有1个驱动程序。怎么做?

2 个答案:

答案 0 :(得分:3)

select 
  count(driver_id) as `drivers`,
  agent_id
  from driver
  group by agent_id

答案 1 :(得分:1)

你需要这个:

  SELECT agent_id, COUNT(driver_id) AS `drivers`
  FROM driver
  GROUP BY agent_id

输出如:

--------+---------+
agent_id|drivers  |
--------+---------+
1       |   1     |
2       |   3     |
--------+---------+

click the sqlfiddle here