MySQL(MyISAM) - 将字段更新为来自不同表的两个字段中的最大字段

时间:2010-07-16 20:23:14

标签: mysql multi-table

我有两个表,t1t2,每个表有两列 - id_userage
如果t1.age中没有匹配的ID,如何将t1.age更新为最大t2.aget1.age以匹配ID并保持t2不变。

更新前:

t1  
+-------+---+   
|id_user|age|  
+-------+---+   
|      1|  5|  
+-------+---+   
|      2| 10|  
+-------+---+   
|      3| 10|  
+-------+---+   

t2
+-------+---+   
|id_user|age|  
+-------+---+   
|      2| 12|  
+-------+---+   
|      3|  8|  
+-------+---+   
|      4| 20|  
+-------+---+   

更新后:

t1  
+-------+---+   
|id_user|age|  
+-------+---+   
|      1|  5|  
+-------+---+   
|      2| 12|  
+-------+---+   
|      3| 10|  
+-------+---+   

2 个答案:

答案 0 :(得分:2)

您可能想尝试:

UPDATE  t1
JOIN    t2 ON (t2.id_user = t1.id_user)
SET     t1.age = t2.age
WHERE   t2.age > t1.age;

测试用例:

CREATE TABLE t1 (id_user int, age int);
CREATE TABLE t2 (id_user int, age int);

INSERT INTO t1 VALUES (1, 5);
INSERT INTO t1 VALUES (2, 10);
INSERT INTO t1 VALUES (3, 10);

INSERT INTO t2 VALUES (2, 12);
INSERT INTO t2 VALUES (3, 8);
INSERT INTO t2 VALUES (4, 20);

结果:

SELECT * FROM t1;
+---------+------+
| id_user | age  |
+---------+------+
|       1 |    5 |
|       2 |   12 |
|       3 |   10 |
+---------+------+
3 rows in set (0.00 sec)

答案 1 :(得分:0)

UPDATE t1
SET age = T2.age
FROM t1
INNER JOIN t2
ON t2.id_user = t1.id_user
WHERE t2.age > t1.age