Possibility of replacing ORDER BY with another value if the 1st value is empty

advertisements

Is it possible to replace value field_id_36 with field_id_39 if field_id_36 is empty?

SELECT wt.title, wt.url_title, wt.weblog_id, wt.entry_id, wd.field_id_36
    FROM exp_weblog_titles wt
    LEFT JOIN exp_weblog_data wd
    ON wt.entry_id = wd.entry_id
    WHERE wt.weblog_id = {weblog_id_insert}
    ORDER BY field_id_36+0

So in theory, this is what I am trying to do:

SELECT wt.title, wt.url_title, wt.weblog_id, wt.entry_id, wd.field_id_36, wd.field_id_39
    FROM exp_weblog_titles wt
    LEFT JOIN exp_weblog_data wd
    ON wt.entry_id = wd.entry_id
    WHERE wt.weblog_id = {weblog_id_insert}
    ORDER BY if(field_id_36)else(field_id_39)+0


Given a sample data:

id_36   id_39
--      --
1       10
4       40
NULL    2
NULL    3

, this query:

SELECT  wt.title, wt.url_title, wt.weblog_id, wt.entry_id, wd.field_id_36, wd.field_id_39
FROM    exp_weblog_titles wt
LEFT JOIN
        exp_weblog_data wd
ON      wt.entry_id = wd.entry_id
WHERE   wt.weblog_id = {weblog_id_insert}
ORDER BY
        COALESCE(field_id_36, field_id_39)

will sort it like this:

id_36   id_39
--      --
1       10
NULL    2
NULL    3
4       40

, while this one:

SELECT  wt.title, wt.url_title, wt.weblog_id, wt.entry_id, wd.field_id_36, wd.field_id_39
FROM    exp_weblog_titles wt
LEFT JOIN
        exp_weblog_data wd
ON      wt.entry_id = wd.entry_id
WHERE   wt.weblog_id = {weblog_id_insert}
ORDER BY
        field_id_36, field_id_39

will sort like this:

id_36   id_39
--      --
NULL    2
NULL    3
1       10
4       40