获取具有外键的表的记录计数

时间:2017-04-17 07:26:04

标签: mysql

我有以下表格:

人:

person_id   |   name    | 
-------------------------
1           |   John    |
2           |   Adam    |
3           |   Elen    |
-------------------------

订单:

order_id    |   person_id   |   product     | 
---------------------------------------------
1           |       1       |   TV          |
2           |       1       |   Radio       |
3           |       1       |   toothbrush  |
4           |       2       |   mp3 player  |
5           |       2       |   watch       |
6           |       3       |   ps 3        |
---------------------------------------------

现在我需要查询上面的表格以获得以下结果:

person_id   |   name    |   order_count |
-----------------------------------------
1           |   John    |       3       |
2           |   Adam    |       2       |
3           |   Elen    |       1       |
-----------------------------------------

我尝试过类似的事情:

SELECT u.person_id, u.name, COUNT(o.order_id) FROM persons AS p LEFT JOIN orders AS o ON (p.person_id=o.person_id);

不幸的是,这不起作用。你知道如何解决这个问题吗?

5 个答案:

答案 0 :(得分:2)

select Persons.person_id, Persons.name, p.order_count 
from Persons
inner join (select person_id, count(*) as order_count from Orders group by person_id) p
on Persons.person_id = p.person_id  

如果您还需要那些没有任何订单的人,请使用left join代替inner join

答案 1 :(得分:0)

尝试这个

SELECT persons.id, persons.name, COUNT(orders.id) AS order_count  FROM orders LEFT JOIN persons ON (persons.person_id=orders.person_id) GROUP BY persons.name

答案 2 :(得分:0)

试试这个......

“从tblorders o选择o.person_id,p.name,count(o.person_id)作为order_count 加入tblpersons p on o.person_id = p.person_id 分组由o.person_id,p.name“

答案 3 :(得分:0)

试试这个

select o.person_id,p.name,count(o.person_id) as order_count from tblorders o 
Join tblpersons p on o.person_id=p.person_id
group by o.person_id,p.name

答案 4 :(得分:-1)

select p.person_id, p.name, o.cnt
from Persons p
left join 
(select person_id  , count(order_id) as cnt from Orders group by person_id) o
on p.person_id = o.person_id