Table A
ID | date
1 | 2014-05-16
2 | 2014-05-15
3 | 2014-05-16
4 | 2014-05-17
5 | 2014-05-18
Table B
ID| A.ID | B.Key | B.KeyValue
1 | 1 | date | 2014-07-23
2 | 3 | date | 2014-07-11
3 | 4 | date | 2013-10-07
Let's say I have two tables, A & B. How do I come up with all of A, but have linked records in B replace the 'date' in A. eg.:
A.1 links up with B.1, and so the new date in A should be 2014-07-23 and not 2014-05-16.
Also, I'd like to have it sorted by the new date. e.g.,
1 | 2014-07-23
3 | 2014-07-11
5 | 2014-05-18
2 | 2014-05-15
4 | 2013-10-07
So far, I have this:
SELECT
DISTINCT A.ID,
IF(B.Key = 'date', IF(B.KeyValue <> '', B.KeyValue, A.date), A.date) new_date
FROM TableA A
LEFT JOIN TableB B ON A.ID = B.ID
ORDER BY new_date DESC
But some how I come up with duplicates for the linked rows.