如何解决根据一个参考表和计数记录联接多个表
我有以下表格:
汽车:
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
所需表:
car_id total_type total_colors
————————————————---------------------------
1 2 3
2 1 1
3 2 0
4 0 1
如何获得结果表?我不希望使用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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。