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

发布于 2024-09-09 17:10:15 字数 747 浏览 3 评论 0原文

我有两个表,t1t2,各有两列 - id_userage
如何将 t1.age 更新为 t1.aget2.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|  
+-------+---+   

I have two tables, t1 and t2 with two columns each - id_user and age.
How do I update t1.age to the greatest of t1.age and t2.age for matching ID's and leave t1.age unchanged if there is no matching ID in t2.

Before update:

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

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

After update:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

彼岸花似海 2024-09-16 17:10:15

您可能想尝试:

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)

You may want to try:

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

Test Case:

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);

Result:

SELECT * FROM t1;
+---------+------+
| id_user | age  |
+---------+------+
|       1 |    5 |
|       2 |   12 |
|       3 |   10 |
+---------+------+
3 rows in set (0.00 sec)
彻夜缠绵 2024-09-16 17:10:15
UPDATE t1
SET age = T2.age
FROM t1
INNER JOIN t2
ON t2.id_user = t1.id_user
WHERE t2.age > t1.age
UPDATE t1
SET age = T2.age
FROM t1
INNER JOIN t2
ON t2.id_user = t1.id_user
WHERE t2.age > t1.age
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文