我有两张相同结构的表:
表:用户
+----+--------+--------------+----------------------+
| 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 |
+----+--------+--------------+----------------------+
表: 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 |
+----+--------+--------------+----------------------+
现在我需要从这两个表中获取最新数据(通过'LastUpdateTime'),如下所示:
+----+--------+--------------+----------------------+
| 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 |
+----+--------+--------------+----------------------+
我尝试过:
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
我不确定这是否合适。此外,我担心大量数据的查询性能。对此有没有更好的方法?
PS :除了姓名&amp;密码两个表中还有十几个字段(列)。我只是为了简化问题而避免使用它们。
答案 0 :(得分:1)
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。:对于id 3,较新的密码实际上是来自用户表的密码,而不是user_k。您想要的结果集需要进行此调整。