B
B
bigtrouble2015-03-04 12:26:58
MySQL
bigtrouble, 2015-03-04 12:26:58

How to select items for which there are currently no records in the database?

Good afternoon, perhaps the title does not fully reflect the essence of the issue, so I will be glad if someone corrects it.
For example, there is a table of users and their orders
Users
id_user | name | ...
500 | Jack | ...
501 | Nick | ....
Orders
id_order | id_user | .... | date | ....
1052 | 500 | .... | 2015-02-23 | ....
1053 | 500 | .... | 2015-02-23 | ....
So, you need to select the number of orders from each user for the last month, the query looks like this

SELECT `users`.`id_user`, count(`orders`.`id_order`) as `sum_orders`
FROM `users`
JOIN `orders` ON (`users`.`id_user` = `orders`.`id_user`)

WHERE `orders`.`date` >= '2015-02-01 00:00:00' AND `orders`.`date` < '2015-03-01 00:00:00' 
group by `users`.`id_user`

It seems that everything is cool and the task is completed, but here the problem arises that users who did not have orders at all are not displayed in this list (and this is understandable why, because they had no orders in the 2nd month). How can I rewrite the query so that user ids with null values ​​are also included?
Yes, a possible solution is to select users with orders, select all users and discard users with orders from all and get users with zero orders, but here another problem arises if, for example, we impose a condition on the selection of users who have less than a given number of orders, for example, add There is also an option to get all users from the database and try to get orders for each, but here there are already too many requests.
having `sum_orders` < 15
then the option of discarding such users is already becoming problematic.
In general, I will repeat on the initial select - How to remake the request in such a way that user ids with zero values ​​​​are also included?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Leonid Sysoletin, 2015-03-04
@bigtrouble

Use LEFT JOIN?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question