views:

88

answers:

2

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
+1  A: 

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
Quassnoi
This will work only if the value is NULL.
David Basarab
Some items either have id_36 populated w/ values or id_39, not both. But it would be good to plan for the future, if both 36 and 39 had values in each column.
Brad
`COALESCE(field_id_36, field_id_39)` will return the first non-`NULL` value, so just use the first query. You can add additional fields, like `COALESCE(field_id_36, field_id_39, field_id_2)`, in which case it still returns the first non-`NULL` value (in argument order), or a `NULL` if all three are `NULL`.
Quassnoi
+1  A: 

What you want is the CASE Statement

You Order by would look like

ORDER BY 
     CASE 
      WHEN field_id_36 IS NULL 
        THEN WHEN 
            CASE
              WHEN field_id_2 IS NULL
                THEN field_id_39
              ELSE
                 field_id_2    
            END CASE
        WHEN field_id_4 IS NOT NULL
          THEN field_id_4
     ELSE field_id_36 
     END CASE

I expanded this based on the comment. The point is you can nest cases.

David Basarab
Now another question, what if there were three different values. The third being field_id_2, what would the ORDER BY part look like.
Brad
It depends on what you mean. If you say first check field_id_36 then field_id_2 if that is null, you would have a nested Case.
David Basarab
Brad