mysql - 如何在条件聚合mysql中添加where?
问题描述
我的查询是这样的:
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'
我该如何解决这个错误?
解决方案
更改查询的最后一部分
WHERE brand = 'honda'
GROUP BY i.number, i.description
至
GROUP BY i.number, i.description
HAVING brand = 'honda'
推荐阅读
- javascript - 为什么我的替换方法会引发错误?
- java - Java 中的泛型类型推断限制
- angular5 - Angular 5以编程方式获取表单控件的直接formGroup名称
- c# - DataTable.Select() 显示数据表中记录的总和
- objective-c - Obj C 到 Swift 的转换
- mongodb - 如何通过 MongoDB 同步在两个不同服务器上运行的两个应用程序
- sql - 如何获取字符回历日期 SQL Server 的年份
- java - 为什么 System.out.println() 中不需要 java.io.PrintStream?
- jquery - Aframe 设备检测
- bash - 使用远程数据扩展 Bash glob 模式