简体   繁体   English

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

[英]How to get a count of each record in mysql query

I have two mysql tables, users and orders to track orders placed by each user. 我有两个mysql表, usersorders以跟踪每个用户下的订单。

I want to get a list of each user, and the total number of orders. 我想获取每个用户的列表以及订单总数。

For an individual, I could use: 对于个人,我可以使用:

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

Is there an efficient way to do this for all users simultaneously? 是否有一种有效的方式可以同时为所有用户执行此操作?

You can do it with a correlated subquery. 您可以使用相关子查询来实现。

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

But a better way is with a join. 但是更好的方法是加入。

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

It may actually be better to join with a subquery that aggregates, rather than aggregating after joining: 实际上,最好使用聚合的子查询进行合并,而不是在合并后进行聚合:

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

The key is really a GROUP BY: 关键确实是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

You could do something like that too, in this case only will return when there are records on order : 您也可以执行类似的操作,在这种情况下,只有在订单上有记录时才会返回:

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

    group by users.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM