Reputation: 9370
I have two tables with identical structure like this:
Table : user
+----+--------+--------------+----------------------+
| ID | Name | Password | LastUpdateTime |
+----+--------+--------------+----------------------+
| 1 | abu | abu123NEW | 2014-06-04 14:55:06 |
| 2 | john | john123 | 2014-06-04 14:58:22 |
| 3 | shane | shane123 | 2014-06-04 15:02:06 |
| 4 | marie | marie123 | 2014-06-04 15:00:06 |
| 5 | mike | mike123NEW | 2014-06-04 15:01:32 |
| 6 | kiron | kiron123NEW | 2014-06-04 15:05:46 |
+----+--------+--------------+----------------------+
Table : user_k
+----+--------+--------------+----------------------+
| ID | Name | Password | LastUpdateTime |
+----+--------+--------------+----------------------+
| 1 | abu | abu123 | 2014-06-04 14:53:06 |
| 2 | john | john123NEW | 2014-06-04 14:59:48 |
| 3 | shane | shane123NEW | 2014-06-04 15:00:06 |
| 4 | marie | marie123NEW | 2014-06-04 15:03:17 |
| 5 | mike | mike123 | 2014-06-04 15:00:36 |
| 6 | kiron | kiron123 | 2014-06-04 15:02:18 |
+----+--------+--------------+----------------------+
Now I need to fetch the latest data (by 'LastUpdateTime') from these two tables, like this:
+----+--------+--------------+----------------------+
| ID | Name | Password | LastUpdateTime |
+----+--------+--------------+----------------------+
| 1 | abu | abu123NEW | 2014-06-04 14:55:06 |
| 2 | john | john123NEW | 2014-06-04 14:59:48 |
| 3 | shane | shane123 | 2014-06-04 15:02:06 |
| 4 | marie | marie123NEW | 2014-06-04 15:03:17 |
| 5 | mike | mike123NEW | 2014-06-04 15:01:32 |
| 6 | kiron | kiron123NEW | 2014-06-04 15:05:46 |
+----+--------+--------------+----------------------+
What I have tried:
SELECT uk.* FROM user AS ua, user_k AS uk
WHERE uk.ID = ua.ID AND uk.LastUpdateTime > ua.LastUpdateTime
UNION
SELECT ua.* FROM user AS ua ,user_k AS uk
WHERE uk.ID = ua.ID AND uk.LastUpdateTime < ua.LastUpdateTime
I'm not sure if this is the appropriate way. Also I'm concerned about the query performance with large set of data. Is there any better approach for this?
PS: Besides name & password there are a dozen more fields(columns) in both tables. I avoid them just to simplify the question.
Upvotes: 0
Views: 342
Reputation: 51868
select
u.id,
u.name,
if(u.LastUpdateTime >= k.LastUpdateTime, u.password, k.password) as password,
greatest(u.LastUpdateTime, k.LastUpdateTime) as LastUpdateTime
from
user u
inner join user_k k on u.id = k.id
P.S.: For id 3 the newer password is actually the one from user table, not user_k. Your desired result set needs this adjustment.
Upvotes: 1