سؤال

I have this query:

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;

When no join occurs and the result is NULL I expected the query to COALESCE the null result with "NONE", however I still get NULL. How would I make it such that "NONE" is returned instead of NULL?

I neglected to explain an important point: usaf and wban are IN variables to a stored procedure. Here is my final (working) version. Thanks 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
هل كانت مفيدة؟

المحلول 2

Supply the Ar alias in the WHERE clause

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;

Looking at this query, you could improve the JOIN even more in three(3) ways

First, add the WHERE clause elements into the ON section of the JOIN

Second, make it a LEFT JOIN so as to accommodate NULL situations

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;

Third, add these indexes

ALTER TABLE `metadata`.`ISH-HISTORY_HASPOS` ADD INDEX (mergeId,usaf,wban);
ALTER TABLE `metadata`.`Artificial` ADD INDEX (id,usaf,wban);

Give it a Try !!!

نصائح أخرى

The query never considers a NULL value of usaf and wban because of the where clause:

WHERE A.usaf = usaf AND A.wban = wban;

When these columns are NULL, then the row is filtered out. This is even true for the tautology a.usaf = a.usaf. That statement returns FALSE (well, NULL) when a.usaf is NULL.

Remove the where clause and the query will probably work as you expect.

As a second comment . . . do you want an inner join or a left outer join?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top