Question

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 ?

Était-ce utile?

La solution 2

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

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top