A
A
Albert Tobacco2015-10-26 18:10:34
PostgreSQL
Albert Tobacco, 2015-10-26 18:10:34

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;

But I get the wrong result, everything is fine if you do only one join, the second one breaks everything. I will be grateful for help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aleksey Ratnikov, 2015-10-26
@bighoc

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;

E
eldar_web, 2015-10-26
@eldar_web

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;

N
nozzy, 2015-10-26
@nozzy

possible with union all:
SELECT COUNT(id) AS first_table_id, NULL AS second_table_id
FROM table1
WHERE model_id = 781
UNION ALL
SELECT NULL AS first_table_id, COUNT(id) AS second_table_id
FROM table2
WHERE model_id = 781

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question