我有两个表,t1
和t2
,每个表有两列 - id_user
和age
。
如果t1.age
中没有匹配的ID,如何将t1.age
更新为最大t2.age
和t1.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| +-------+---+
答案 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