Answer the question
In order to leave comments, you need to log in
How to execute a subquery in SQL (SELECT passing parameter from main query?
Please tell me how to solve this problem.
Conditionally, there is a table Users
id, name
There is a table Orders
id, number, user_id
I want to calculate the number of orders for each user through a subquery.
Something like
select users.name as username,
(select count(id) from orders where user_id=users.id) as orders_count
from
users
subqueries are executed from the bottom up, users.id cannot be passed to the subquery.
Yes, you can do a join, but I have a problem with it, because in my case, it is already there according to other criteria with the same tables, according to which I want to calculate the data, in general, some other mechanism is needed. Those.
Answer the question
In order to leave comments, you need to log in
select u.name as username,
(select count(id) from orders where user_id=u.id) as orders_count
from users u
SELECT users.name AS username,
count(orders.id) AS orders_count
FROM users
JOIN orders ON orders.user_id=users.id
GROUP BY users.name
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question