Answer the question
In order to leave comments, you need to log in
How to create a query with a criterion in another table?
Good afternoon friends.
Initial data:
Table Users
user_id name
1 Vitya
2 Ivan
3 Vasya
Children table (children) contains id, id of the parent (user_id), as well as a flag indicating whether the current child has children (has_child 1-yes, 0-no)
ch_id user_id has_child
1 | 1 | 0
2 | 1 | 0
3 | 2 | 1
4 | 2 | 0
5 } 2 | one
My task is to get user IDs from the first table who do not have grandchildren. Accordingly, users Vitya and Vasya (id = 1, id = 3) will get here. Vitya has two children, but these children do not have children of their own. Vasya just does not have children, respectively, and no grandchildren.
So far, I have solved this problem in two stages. The first one got a list of all users, and then looped through the children table with such SELECT * from children WHERE user_id = : user_id AND has_child = 1, if at least one record was returned, then the user has grandchildren and I don’t need him.
Now the tables have become large, and it has become costly to shove the query inside the cycle.
Thanks in advance for your help
Answer the question
In order to leave comments, you need to log in
SELECT u.*, COUNT(c.has_child) as sum, SUM(c.has_child) as sum2 FROM users as u LEFT JOIN children as c ON (c.user_id = u.id) GROUP BY c.user_id HAVING (sum = 0 OR sum2 = 0)
there is a series of good articles on habré habrahabr.ru/post/190396
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question