如果我有一个包含如下字段的查找表:
id, color_id, size_id, 价格
我可以使用以下方法轻松获得特定颜色的所有尺码/价格:
SELECT size_id, price from TABLE where color_id = 2
但是,如果我想像这样显示价格表:
red blue green yellow
xs 1.20 1.20 1.29 1.39
sm 1.40 1.40 1.49 1.59
md 1.40 1.40 1.19 1.59
lg 1.55 1.55 1.80 1.94
xl 1.55 1.55 1.80 1.99
xx 2.01 2.05 2.40 2.68
有没有一种方法可以做到这一点而无需对每种颜色进行查询?或者是否有更好的方法来构建数据?
感谢您的帮助!
最佳答案
select size_id, sum(if(color_id=1,price,0)) c1, sum(if(color_id=2,price,0)) c2, sum(if(color_id=3,price,0)) c3, sum(if(color_id=4,price,0)) c4 from TABLE group by size_id
如果您没有可变数量的颜色,至少这很有效。
关于mysql - 多个产品的最佳查找表查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319777/