如何获取mysql查询中每条记录的计数

时间:2018-01-05 22:59:25

标签: mysql

我有两个mysql表usersorders来跟踪每个用户下的订单。

我想获得每个用户的列表以及订单总数。

对于个人,我可以使用:

SELECT users.name, (select count(*) from orders where orders.users_id = 1) as total
from users
where users.id = 1

是否有一种有效的方法可以同时为所有用户执行此操作?

3 个答案:

答案 0 :(得分:4)

您可以使用相关子查询来完成。

SELECT users.name, (select count(*) from orders where orders.users_id = users.id) as total
from users

但更好的方法是加入。

SELECT users.name, IFNULL(COUNT(orders.id), 0) AS total
FROM users
LEFT JOIN orders ON orders.users_id = users.id
GROUP BY users.id

加入一个聚合的子查询实际上可能更好,而不是在加入后聚合:

SELECT u.name, IFNULL(o.total, 0) AS total
FROM users as u
LEFT JOIN (
    SELECT users_id, COUNT(*) AS total
    FROM orders
    GROUP BY users_id) AS o ON u.id = o.users_id

答案 1 :(得分:1)

密钥实际上是GROUP BY:

SELECT u.id, u.name, COUNT(*)
FROM users u
INNER JOIN orders o ON u.id = o.users_id
GROUP BY u.id, u.name

答案 2 :(得分:-1)

您也可以这样做,在这种情况下,只有在订单中有记录时才会返回:

   SELECT users.name, count(*) 
     from users
     join orders On orders.users_id = users.id  

    group by users.name