I have 2 tables users and orders, I want get users and his orders count
SELECT `users`.*, `orders`.*,count(*) FROM `users` LEFT JOIN orders ON
`users`.`id` = `orders`.`user_id`
UNION SELECT `users`.*, `orders`.*,count(*) FROM users
RIGHT JOIN orders ON `users`.`id` = `orders`.`user_id`
This query select users and order count of users which have order, but not select users who not have orders .
What I want get
user orders
John 5
Thomas 0
Mike 8
What I get
user orders
John 5
Mike 8
How to get also users who not have orders ?
You don't need a full outer join for this. A left outer join should be fine, assuming that all the users in the orders
table have a valid reference to the users
table:
SELECT u.*, count(o.user_id)
FROM `users` u LEFT JOIN
orders o
ON u.`id` = o.`user_id`
group by u.id
The following query will give you a list of all users and the count of their orders, including 0 if that user has no orders.
Also, are you sure that ORDER_ID is the FK to the user table? That seems counter-intuative to me...
SELECT U.NAME
,COUNT(O.ORDER_ID)
FROM USERS U
LEFT OUTER JOIN
ORDERS O
ON U.ID = O.ORDER_ID
GROUP BY
U.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.