I have two mysql tables, users
and orders
to track orders placed by each user.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.