MySQL:仅使用一个FK记录更新记录

时间:2018-01-30 19:37:38

标签: mysql sql

我有两张桌子。 表A具有以下内容:

UserID | ActiveFlag
000001 |    1
000002 |    1
000003 |    1
000004 |    1

表B:

ID      | UserID    |   CustomerId
1       | 000001    |  10
2       | 000002    |  10
3       | 000002    |  11
4       | 000003    |  11

我想将ActiveFlag中的Table A列更新为0,其中table B中的用户CustomerID 10且仅10 {1}}。这意味着,在示例中,UserID 000002Table B中有两条记录:CustomerID 1011。我不想更新00002中的table A

3 个答案:

答案 0 :(得分:1)

10,只有10

update table a set activeflag = o where a.userid in 
(
select b.userid from table b group by b.userid 
having min(b.customerid) = max(b.customerid) 
and min(b.customerid) = 10
)

答案 1 :(得分:0)

脑海中浮现出

exists

update tablea a
     set activeflag = 0
     where a.activeflag <> 0 and
           exists (select 1 from b where b.userid = a.userid and b.customerid = 10) and
           not exists (select 1 from b where b.userid = a.userid and b.customerid <> 10);

答案 2 :(得分:-2)

试试这个:

UPDATE tableA 
SET ActiveFlag = 0
WHERE UserID IN (
   SELECT UserID 
   FROM tableB 
   WHERE CustomerId = 10);

原则是:

  1. 它会过滤掉表B中UserID = 10的所有CustomerId,即000001(ID = 1)和000002(ID = 2)

  2. 检查步骤1中的每个UserID,设置ActiveFlag = 0。即表A中的前两行已更新