如何优化多Physique值场景下的SQL关联查询脚本?
优化多Physique值的SQL查询写法
针对你遇到的18种Physique值需要多次关联t1表的问题,最优解法是用条件聚合(行转列),只需要关联一次t1表,既避免多次join的繁琐,也不会产生笛卡尔积导致行膨胀。
条件聚合写法(通用所有SQL数据库)
select t2.ItemID, t2.Name, max(case when t1.Physique = 'Width' then t1.Target end) as Width, max(case when t1.Physique = 'Length' then t1.Target end) as Length, -- 依次添加剩下的16种Physique对应的case语句 max(case when t1.Physique = 'Height' then t1.Target end) as Height, max(case when t1.Physique = 'Weight' then t1.Target end) as Weight -- ... 其他Physique字段 from t2 left join t1 on t1.ItemID = t2.ItemID group by t2.ItemID, t2.Name
写法说明:
- 仅需一次
t2 left join t1,通过case when筛选不同Physique对应的Target值 - 用
max()(或sum(),因每个ItemID+Physique组合唯一,不会出现多值冲突)聚合,确保每个ItemID对应一行数据 - 对比多次left join,代码更简洁,查询性能更优,不会因多表关联产生额外性能损耗
数据库原生PIVOT写法(部分数据库支持)
如果你的数据库支持PIVOT语法(如SQL Server、Oracle、PostgreSQL 11+),也可以用更简洁的PIVOT实现:
以SQL Server为例:
select ItemID, Name, Width, Length, Height, Weight -- ... 其他Physique字段 from ( select t2.ItemID, t2.Name, t1.Physique, t1.Target from t2 left join t1 on t1.ItemID = t2.ItemID ) as src pivot ( max(Target) for Physique in (Width, Length, Height, Weight) -- 列出所有18种Physique值 ) as pvt
注意事项:
- PIVOT语法在不同数据库中有细微差异,需根据使用的数据库调整
- 同样仅需一次关联子查询,逻辑更清晰
内容的提问来源于stack exchange,提问作者Niek
相关产品推荐
相关产品推荐

