У меня есть 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;
LOL, если это так просто, то будет лучше, если я перестану программировать. Спасибо работает ;)
SELECT brands.brand_id, brands.brand_name, brands.brand_country_id, country.country_id, country.country_niename ,temp.whiskycount
FROM brands LEFT JOIN country ON brands.brand_country_id = country.country_id
LEFT JOIN (
select count(*) as whiskycount, whisky_brand_id
from whisky
Group by whisky_brand_id
) temp ON brands.brand_id = whisky.whisky_brand_id
ВЫБЕРИТЕ brands.brand_id, brands.brand_name, brands.brand_country_id, country.country_id, country.country_niename, temp.whiskycount ИЗ brands LEFT JOIN country ON brands.brand_country_id = country.country_id LEFT JOIN (выберите count(*) как вискиколичество, виски_brand_id из Группа виски по виски_brand_id ) temp ON brands.brand_id = виски.whisky_brand_id