我有一个包含两个表用户和订单的数据库
users: user_id(primary), fname, lname, email, password, gender
orders: order_no(primary), user_id(foriegn), beans, type, extras, city
订单表只有提交订单的用户。
我需要知道如果他们有订单或者没有订单,如何选择所有用户的订单数。
user_id fname lname email password gender
1 a aa aaa 123 m
2 b bb bbb 34 f
order_no user_id bean type extras city
1 2 s d rr ggg
2 2 s d rr ggg
如何选择所有用户表格列以及a和b的订单计数,以便新表格为:
user_id fname lname email password gender orders_count
1 a aa aaa 123 m 0
2 b bb bbb 34 f 2
答案 0 :(得分:3)
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
答案 1 :(得分:0)
您的更新基本上是在请求pcofre's answer已经提供给您的内容。您只需将所需的其他列添加到select
列表中,并为聚合提供列别名。
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*/
答案 2 :(得分:0)
根据更新的信息,使用:
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