简体   繁体   中英

SORT BY date in left+right union join table

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 code ORDER BY correctly in that situation? Thanks alot!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM