sql - 如何计算第二个表中给定 id 的命中次数
问题描述
我有 3 张桌子,比如“品牌”、“威士忌”和“国家”
品牌
brand_id brand_name brand_country_id
1 Example brand 1
2 Brand 2 2
威士忌酒
whisky_id whisky_brand_id
1 2
2 2
3 1
4 2
国家
country_id country_nicename
1 Poland
2 Germany
我有 SQL:
SELECT
brands.brand_id,
brands.brand_name,
brands.brand_country_id,
country.country_id,
country.country_niename
FROM
brands
LEFT JOIN
country
ON
brands.brand_country_id = country.country_id
LEFT JOIN
whisky
ON
brands.brand_id = whisky.whisky_brand_id
我想要像这样的数据
brand_id brand_name country_id country_nicename no.ofWhisky
2 Brand2 1 Germany 3
但我不知道如何在这个查询中计算威士忌的数量:/有人可以帮忙吗?谢谢 :)
解决方案
您只需要使用group by
&进行聚合count()
:
SELECT brands.brand_id, brands.brand_name, country.country_id, country.country_niename,
count(whisky_id) as no.ofWhisky
FROM brands LEFT JOIN
country
ON brands.brand_country_id = country.country_id LEFT JOIN
whisky
ON brands.brand_id = whisky.whisky_brand_id
GROUP BY brands.brand_id, brands.brand_name, country.country_id, country.country_niename;
推荐阅读
- python - 模板中未显示 Django 表单验证错误
- laravel - 使用actingAs的测试方法存在问题
- python - 如何在 Excel 电子表格中使用 x/y/r 像素坐标在 Python 中裁剪多个图像?
- tensorflow - TensorFlow 自动分割图像
- java - Application crashes when item from searchable spinner is selected
- java - i am trying get last two character of the String but i am getting error
- sql - Recursion for forming groups
- google-cloud-platform - Dataproc 覆盖执行程序内存
- javascript - 更新我的正则表达式以包含点和连字符
- java - regionMatches() 方法中的任何参数都可以使该方法对大写和小写的字符串返回 true 吗?