JOIN multiple tables based on one reference table and count records
JOIN multiple tables based on one reference table and count records
我有以下 tables:
汽车:
id manufacturer
--------------------
1 Nissan
2 Toyota
3 Honda
4 Volkswagen
类型:
id type car_id
--------------------------------------------
1 maxima 1
2 civic 3
3 accord 3
4 corolla 2
5 altima 1
颜色:
id color car_id
———————————--------------------
1 yellow 1
2 blue 2
3 blue 1
4 black 4
5 red 1
想要table:
car_id total_type total_colors
————————————————---------------------------
1 2 3
2 1 1
3 2 0
4 0 1
我怎样才能得到结果 table?我不想使用 with 子句。 CROSS JOIN
是最佳方式吗?
似乎可以使用 2 个 LEFT JOIN 和 COUNT DISTINCT 聚合函数来完成。像这样
select c.id, count(distinct t.id) total_type, count(distinct co.id) total_colors,
from cars c
left join [types] t on c.id=t.car_id
left join colors co on c.id=co.car_id
group by c.id
order by 1;
我有以下 tables:
汽车:
id manufacturer
--------------------
1 Nissan
2 Toyota
3 Honda
4 Volkswagen
类型:
id type car_id
--------------------------------------------
1 maxima 1
2 civic 3
3 accord 3
4 corolla 2
5 altima 1
颜色:
id color car_id
———————————--------------------
1 yellow 1
2 blue 2
3 blue 1
4 black 4
5 red 1
想要table:
car_id total_type total_colors
————————————————---------------------------
1 2 3
2 1 1
3 2 0
4 0 1
我怎样才能得到结果 table?我不想使用 with 子句。 CROSS JOIN
是最佳方式吗?
似乎可以使用 2 个 LEFT JOIN 和 COUNT DISTINCT 聚合函数来完成。像这样
select c.id, count(distinct t.id) total_type, count(distinct co.id) total_colors,
from cars c
left join [types] t on c.id=t.car_id
left join colors co on c.id=co.car_id
group by c.id
order by 1;