select from two tables using subquery
I have a dat开发者_JAVA百科abase with two tables users and orders
users: user_id(primary), fname, lname, email, password, gender
orders: order_no(primary), user_id(foriegn), beans, type, extras, city
The orders table have only users who submitted orders.
I need to know how to select all users with the count of their orders if they have orders or don't.
Additional Info posted as an answer....
users table:
user_id fname lname email password gender
1 a aa aaa 123 m
2 b bb bbb 34 f
orders table:
order_no user_id bean type extras city
1 2 s d rr ggg
2 2 s d rr ggg
how to select all users table columns plus orders count for a and b so the new table will be:
user_id fname lname email password gender orders_count
1 a aa aaa 123 m 0
2 b bb bbb 34 f 2
select U.user_id,
COUNT(O.user_id)
from users U
left join orders O on U.user_id=O.user_id
group by U.user_id
Based on the updated information, use:
SELECT u.*,
COALESCE(x.orders_count, 0) AS orders_count
FROM USERS u
LEFT JOIN (SELECT o.user_id,
COUNT(*) AS orders_count
FROM ORDERS o
GROUP BY o.user_id) x ON x.user_id = u.user_id
ORDER BY u.user_id
Your update is basically requesting what pcofre's answer already gives you. You just need to add the additional required columns to your select
list and provide a column alias for the aggregate.
SELECT U.user_id,
U.fname,
U.lname,
U.email,
U.password,
U.gender,
COUNT(O.user_id) AS orders_count
FROM users U
LEFT JOIN orders O
ON U.user_id = O.user_id
GROUP BY U.user_id /*<-- Don't need to add other users
columns to GROUP BY in MySQL*/
精彩评论