我有3张桌子:
TableA TableB TableC
Col1 ID Col1 ID TableA.ID
Col2 NAME Col2 NAME TableB.ID
Col3 STATUS
如果table.c包含TableA.ID和TableB.Id,TableB.Name =“test”,我想将TableA.Col3设置为null。可能吗?
你可以做:
update tablea a
join tablec c on c.tablea_id = a.id
join tableb b on b.id = c.tableb_id
set status = null
where b.name = 'test'
结果:
id name status
-- ------ ------
10 Peter 1
20 Anne null
30 Claire 3
我使用的数据是:
create table tablea (
id int,
name varchar(10),
status int
);
create table tableb (
id int,
name varchar(10)
);
create table tablec (
tablea_id int,
tableb_id int
);
insert into tablea (id, name, status) values (10, 'Peter', 1);
insert into tablea (id, name, status) values (20, 'Anne', 2);
insert into tablea (id, name, status) values (30, 'Claire', 3);
insert into tableb (id, name) values (101, 'one');
insert into tableb (id, name) values (102, 'test');
insert into tablec (tablea_id, tableb_id) values (10, 101);
insert into tablec (tablea_id, tableb_id) values (20, 102);
insert into tablec (tablea_id, tableb_id) values (30, 101);
使用Update
尝试Join
UPDATE TableA T1
JOIN TableB T2 on T1.ID = T2.ID
JOIN TableC T3 on T1.ID = T3.ID
SET T1.STATUS = NULL
WHERE T2.Name = 'test'
我会为此目的推荐exists
:
update tablea
set status = null
where exists (select 1
from tablec c join
tableb b
on b.id = c.tableb_id
where tablea.id = c.tablea_id and b.name = 'test'
);
这应该适用于任何数据库。它还为优化器提供了更多空间来查找最佳查询计划。
这样的事情应该做到这一点。
UPDATE tableA as t
Set Status=NULL from TableA t
left join TableC tc on t.ID=tc.tablea_id
left join tableb tb on tb.id=tc.tableb_id
where tc.tablea_id is not null and tb.name='test'