我有以下结构的SQL数据:
Car_Color | Model_tag
----------------------
Green | Fairytail1
Red | Tail2
Blue | Fairy3
Green | Hi3
Green | Test45
Green | Testing34
我想得到如下输出返回以下查询:找到至少四关联的model_tag的car_color的所有名称,对于这些颜色,每个写入的model_tags的数量car_color。
Car_Color | number_of_tags
----------------------------
Green | 4
这是我的问题:
SELECT car, model_tag
FROM Model
问题是以下查询不会返回任何数据。
答案 0 :(得分:4)
修复聚合逻辑:
SELECT c.car_color, COUNT(mt.tag_name) as numer_of_tags
FROM Model m JOIN
model_tag mt
ON mt.tag_id = m.model_id JOIN
car c
ON c.car_color_id = m.model_id
GROUP BY c.car_color
HAVING COUNT(mt.tag_name) >= 4;
答案 1 :(得分:0)
如果你对model_tag.tag_name进行分组,我认为你不能得到所需的输出,试试这个:
SELECT car.car_color, COUNT (model_tag.tag_name) as numer_of_tags
FROM Model
JOIN model_tag ON model_tag.tag_id = model.model_id
JOIN car ON car.car_color_id = model.model_id
GROUP BY car.car_color
HAVING COUNT(car.car_color_id)>=4
答案 2 :(得分:0)
试试这个,我其实只是复制了上面的答案并放入了DISTINCT
SELECT c.car_color, COUNT(DISTINCT mt.tag_name) as numer_of_tags
FROM Model m JOIN
model_tag mt
ON mt.tag_id = m.model_id JOIN
car c
ON c.car_color_id = m.model_id
GROUP BY c.car_color
HAVING COUNT(DISTINCT mt.tag_name) >= 4;