0

I have 2 tables with lots of identical data (applies for manufacturing of businesscards in 2 languages).

I JOIN (emulate FULL OUTER join as far as i know, doing LEFT UNION RIGHT JOIN) them to show the data side by side for easy copying.

table a has data in language1
table b has data in language2

Not every person have both language1 and language2 data, so have just language1 or just language2.

I do a query like that:

SELECT
<long list of selected rows from table a and table b as afiled,bfield>
FROM tablelanguage1 a 
LEFT JOIN tablelanguage2 b
ON a.email=b.email
UNION
SELECT<long list of selected rows from table a and table b as afiled,bfield>
FROM tablelanguage1 a 
RIGHT JOIN tablelanguage2 b
ON b.email = a.email
ORDER BY adatetime DESC, bdatetime DESC

This shows everything just as i need but i have troubles with sorting: it shows everything but language2-only entries correctly. Language2-only(table b) entries are always last, even if the date is later than some of language1+language2 or language1-only entries.

Any suggestions on how to codeORDER BY correctly in that situation? Thanks alot!

4

1 回答 1

0

You can fix this with the COALESCE() function:

ORDER BY COALESCE(adatetime,bdatetime) DESC

COALESCE() returns the first non-NULL value from a set. The result you were getting makes sense, because for all those 'language2-only' records the adatetime was NULL. Multiple fields in ORDER BY are treated as a heirarchy, so all those NULL values get sorted together, then it considers the bdatetime value. COALESCE() will order all records by whichever date is populated, instead of first one then the other.

于 2013-07-22T17:45:21.460 回答