如何在条件聚合mysql中添加where?

h9a6wy2h  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(329)

这个问题在这里已经有答案了

在mysql查询的where子句中使用列别名会产生错误(8个答案)
两年前关门了。
我的问题是这样的:

SELECT a.number, a.description, b.attribute_code, b.attribute_value 
FROM items a 
JOIN attr_maps b ON b.number = a.number WHERE a.number = AB123

如果执行查询,结果如下:

我想得出这样的结果:

我使用如下条件聚合:

SELECT i.number, i.description,
       MAX(CASE WHEN am.attribute_code = 'brand' then am.attribute_value END) as brand,
       MAX(CASE WHEN am.attribute_code = 'model' then am.attribute_value END) as model,
       MAX(CASE WHEN am.attribute_code = 'category' then am.attribute_value END) as category,
       MAX(CASE WHEN am.attribute_code = 'subcategory' then am.attribute_value END) as subcategory
FROM items i JOIN
     attr_maps am
     ON am.number = i.number
WHERE i.number = AB123
GROUP BY i.number, i.description

它起作用了
但我还是很困惑的补充 where 条件。所以我想它可以过滤品牌等
我试着这样:

SELECT i.number, i.description,
       MAX(CASE WHEN am.attribute_code = 'brand' then am.attribute_value END) as brand,
       MAX(CASE WHEN am.attribute_code = 'model' then am.attribute_value END) as model,
       MAX(CASE WHEN am.attribute_code = 'category' then am.attribute_value END) as category,
       MAX(CASE WHEN am.attribute_code = 'subcategory' then am.attribute_value END) as subcategory
FROM items i JOIN
     attr_maps am
     ON am.number = i.number
WHERE brand = 'honda'
GROUP BY i.number, i.description

存在错误 Unknown column 'brand' in 'where clause' 如何解决错误?

oxiaedzo

oxiaedzo1#

更改查询的最后一部分

WHERE brand = 'honda'
GROUP BY i.number, i.description

GROUP BY i.number, i.description
HAVING brand = 'honda'

相关问题