Answer the question
In order to leave comments, you need to log in
How to form a SQL query?
There are two tables in mysql:
table1
-------
id
name
table2
-------
id
name
table1_id
filter
It is necessary to form a query that would return all records from the first table with an additional column in which the number of records is calculated in the second table that refer to the first and at the same time satisfy a certain filter). It should be noted that in the second table for a specific record from the first one there may either not be at all referring to it, or they may not satisfy the filter and 0 should be entered for such records.
I have been trying for several hours and I can’t make such a request.
Answer the question
In order to leave comments, you need to log in
SELECT table1.*, (SELECT count(id) FROM table2 WHERE table1_id=table1.id AND filter...)
FROM table1
SELECT JOIN COUNT GROUP BY and finally WHERE or HAVING - and everything will work out.
show what you have drawn - otherwise this is not a question, but a task.
SELECT t1.id, t1.name, COUNT(t2.id)
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.table1_id AND t2.filter = 'Ваше условие'
GROUP BY t1.id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question