mysql
SELECT * FROM media
LEFT JOIN media_priority
ON (media_priority.media_id = media.id AND media_priority.media_tag = '".$tag."')
WHERE something = 'something'
ORDER BY media_priority.media_order;
This works fine except that media_priority.media_order sometimes comes back as null and mysql puts the null values at the top.
So I was trying to figure out how to do an IS NULL AS tempcol statement with my left join so I can order by that first.....I just can't seem to get the syntax right.
Where would I put the IS NULL statement in my query above?
I was thinking something like:
LEFT JOIN media_priority
ON (media_priority.media_id = media.id AND media_priority.media_tag = '".$tag."')
media_priority.media_order IS NULL AS isnull
but that doesn't work.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
If you specify the ORDER BY clause, NULL values by default are ordered as less than values that are not NULL. Using the ASC order, a NULL value comes before any non-NULL value; using DESC order, the NULL comes last.
Left Join returns a null even when the match exists.
When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL.
I recommend ordering by the boolean value of media_priority.media_order IS NULL
first, then the column value, in order to force the NULLs to the end.
Like this:
SELECT * FROM media
LEFT JOIN media_priority
ON (media_priority.media_id = media.id AND media_priority.media_tag = '".$tag."')
WHERE something = 'something'
ORDER BY (media_priority.media_order IS NULL) ASC, media_priority.media_order ASC;
ORDER BY
CASE WHEN media_priority.media_order IS NULL THEN 1 ELSE 0 END,
media_priority.media_order;
Or use a magic number if you have some upper limit which media_order
will never feasibly reach.
ORDER BY
COALESCE( media_priority.media_order,99999999);
The first approach is obviously somewhat safer!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With