我需要有关原始SQL查询的帮助,该查询根据另一个值获取值。
我有以下原始SQL查询。
SELECT pmPropDef.id, pmPropDef.name, pmPropDef.units, pmPropShort.str, pmPropLong.str
FROM pmProp INNER JOIN pmPropDef ON pmProp.propid=pmPropDef.id AND pmPropDef.name = 'Area'
LEFT JOIN pmPropShort ON sid=pmProp.value
LEFT JOIN pmPropLong ON lid=-pmProp.value
WHERE pmProp.ownertype='variant' AND pmPropDef.id = pmProp.propid;
这导致以下结果:
+----+------+-------+------+------+
| id | name | units | str | str |
+----+------+-------+------+------+
| 14 | Area | mm2 | 1.1 | NULL |
+----+------+-------+------+------+
我得到了pmPropShort.str和pmPropLong.str的问题,我应该打赌一个或另一个。我真正想要的是一个单一的价值?如何重新编写此查询以满足我的需求?
答案 0 :(得分:2)
您可以使用COALESCE
返回第一个非NULL参数。例如。
COALESCE(pmPropShort.str, pmPropLong.str)
答案 1 :(得分:0)
你有明显的优先权吗?
示例如果long是优先级
SELECT pmPropDef.id, pmPropDef.name, pmPropDef.units,
IF(pmPropLong.str IS NOT NULL,pmPropLong.str,pmPropShort.str) as str
FROM ...rest of your query