我有两个表,t1
和 t2
,每个表有两列 - id_user
和 age
。
如何将 t1.age
更新为 t1.age
和 t2.age
中的最大值以匹配 ID,并保留 t1.age
如果 t2
中没有匹配的 ID,则不变。
更新前:
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| +-------+---+
最佳答案
你可能想试试:
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)
关于MySQL (MyISAM) - 将字段更新为来自不同表的两个字段中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3268588/