gpt4 book ai didi

如果不存在则更新 MYSQL 否则什么也不做

转载 作者:行者123 更新时间:2023-11-29 03:34:58 25 4
gpt4 key购买 nike

我的问题是如果一个表中的值不存在于另一个表中,我该如何更新它。我检查了INSERT ... ON DUPLICATE KEY UPDATE 但它描述了插入更新而不是插入的内容。

我的情况是,我有两个表说 (t1,t2)。如果 t2 中不存在,我想用一个值更新 t1 中的列。否则增加该值并再次尝试更新。 所以我想要类似的东西

update t1 set column = 'value' if it does not exists in t2

谁能提出解决方案

最佳答案

这是一种使用 JOIN 实现的方法。

create table tab1 (id int , val int);
insert into tab1 values (1,1),(2,3),(3,5);

create table tab2 (id int , val int);
insert into tab2 values (4,1),(2,3),(3,5);

在上面的 tab1 (id = 1) 在 tab2 中不可用,使用下面的命令我们可以更新这些值

update tab1 t1
left join tab2 t2 on t1.id = t2.id
set t1.val =
case
when t2.id IS NULL then 8
else t1.val
end

更新命令后的输出看起来像

mysql> select * from tab1 ;
+------+------+
| id | val |
+------+------+
| 1 | 8 |
| 2 | 3 |
| 3 | 5 |
+------+------+

你也可以使用 EXIST,这也比左连接好得多

update tab1 t1 set t1.val = 10
where NOT EXISTS
(
select 1
from tab2 where tab2.id = t1.id
)

关于如果不存在则更新 MYSQL 否则什么也不做,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23733483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com