T
T
Timur Evgazhukov2015-11-26 17:46:47
MySQL
Timur Evgazhukov, 2015-11-26 17:46:47

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

4 answer(s)
A
Alexander Melnichenko, 2015-11-26
@evgajukov

SELECT table1.*, (SELECT count(id) FROM table2 WHERE table1_id=table1.id AND filter...)
FROM table1

M
Max, 2015-11-26
@MaxDukov

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.

D
Dmitry Belyaev, 2015-11-26
@bingo347

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

N
nozzy, 2015-11-26
@nozzy

select 
t1.id,
t1.name,
ifnull(t2.count_table1_id, 0)
from table1 t1
left join (
  select 
  table1_id,
  count(*) as count_table1_id
  from table2
  group by table1_id
) t2 on t1.id = t2.table1_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question