Answer the question
In order to leave comments, you need to log in
How to build SQL which will be the number of matches in other tables?
I have a list of ids (eg 781). And two tables.
table #1
-id
-model_id
-another_field
table #2
-id
-model_id
-another field
Let's say that in table #1 there are three records with model_id = 781, and in table #2 there are six records with model_id = 781.
I want to get : such a roottatt
id | table number 1 | table №2
------+--------------+-------------------
781 | 3 | 6
I do
SELECT t.id, COUNT(table_one.id) , COUNT(table_two.id)
FROM "table" "t"
LEFT JOIN table_one ON t.id = table_one.model_id
LEFT JOIN "table_two" ON t.id = table_two.model_id
WHERE t.id = 781
GROUP BY t.id;
Answer the question
In order to leave comments, you need to log in
So, if I understood the task correctly - you compare the model_id in two tables with a specific id value from the first table:
SELECT id,
(SELECT COUNT(id) FROM table1 WHERE model_id = t1.id) as 'Таблица №1',
(SELECT COUNT(id) FROM table2 WHERE model_id = t1.id) as 'Таблица №2'
FROM table1 as t1
WHERE id = 781;
I can't check so there may be errors.
Try this:
SELECT t1.id, COUNT(t1.id), COUNT(t2.id) FROM table1 AS t1, table2 AS t2 WHERE t1.id = 781 GROUP BY t1.id;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question