我有这个问题:
SELECT
COALESCE(CONCAT(Ar.usaf, '-', Ar.wban),"NONE") AS TABLE_NAME
FROM
`metadata`.`ISH-HISTORY_HASPOS` A
INNER JOIN `metadata`.`Artificial` Ar ON (Ar.id = A.mergeId)
WHERE
A.usaf = usaf
AND A.wban = wban;
当没有连接发生且结果为NULL时,我希望查询COALESCE的结果为“NONE”,但是我仍然得到NULL。 如何使其返回“NONE”而不是NULL?
我忽略了解释一个重要的观点:
usaf
和wban
IN
变量为stored procedure
。
这是我的最终(工作)版本。谢谢Rolando
BEGIN
SET @usaf = usaf;
SET @wban = wban;
SELECT
COALESCE(CONCAT(Ar.usaf, '-', Ar.wban),"NONE") AS TABLE_NAME
FROM
`metadata`.`ISH-HISTORY_HASPOS` A
INNER JOIN `metadata`.`Artificial` Ar ON (Ar.id = A.mergeId AND A.usaf = @usaf AND A.wban = @wban)
LIMIT 1;
END
答案 0 :(得分:3)
由于where
子句,查询从不考虑usaf和wban的NULL值:
WHERE A.usaf = usaf AND A.wban = wban;
当这些列为NULL时,该行将被过滤掉。对于重言式a.usaf = a.usaf
来说,这甚至是正确的。当a.usaf为NULL时,该语句返回FALSE(嗯,NULL)。
删除where
子句,查询可能会按预期工作。
作为第二条评论。 。 。您想要inner join
还是left outer join
?
答案 1 :(得分:1)
在WHERE子句中提供Ar别名
SELECT
COALESCE(CONCAT(Ar.usaf, '-', Ar.wban),"NONE") AS TABLE_NAME
FROM
`metadata`.`ISH-HISTORY_HASPOS` A
INNER JOIN `metadata`.`Artificial` Ar ON (Ar.id = A.mergeId)
WHERE
A.usaf = Ar.usaf
AND A.wban = Ar.wban;
查看此查询,您可以用三(3)种方式更多地改进JOIN
首先,将WHERE子句元素添加到JOIN的ON部分
其次,将其设为LEFT JOIN以容纳NULL
情况
SELECT
COALESCE(CONCAT(Ar.usaf, '-', Ar.wban),"NONE") AS TABLE_NAME
FROM
`metadata`.`ISH-HISTORY_HASPOS` A
LEFT JOIN `metadata`.`Artificial` Ar
ON (Ar.id = A.mergeId) AND A.usaf = Ar.usaf AND A.wban = Ar.wban;
第三,添加这些索引
ALTER TABLE `metadata`.`ISH-HISTORY_HASPOS` ADD INDEX (mergeId,usaf,wban);
ALTER TABLE `metadata`.`Artificial` ADD INDEX (id,usaf,wban);
试一试!!!