【发布时间】:2017-07-21 08:18:37
【问题描述】:
我在数据库 DB1 中有一个表 Tab1:
col1 | col2
--------------
'abc-1' | 11
'abc-2' | 22
'abc-3' | 33
null | 44
null | 55
我想用另一个数据库 (DB2) 中另一个表 (Tab2) 的 col3 列中的数据更新此表中的 col1 列:
col3 | col4 | col5
---------------------
'abc-1' | 1 | 10
'abc-1' | 2 | 10
'abc-2' | 1 | 20
'abc-3' | 1 | 30
'abc-3' | 2 | 30
'abc-3' | 3 | 30
'abc-4' | 1 | 40
'abc-5' | 2 | 60
(col1 中的数据始终仅来自 col3。)
这些表通过两个中间表连接起来:DB1.Tab3:
col6 | col7
----------------
'abc-001' | 11
'abc-002' | 22
'abc-003' | 33
'abc-004' | 44
和 DB2。Tab4:
col8 | col9
----------------
10 | 'abc-001'
20 | 'abc-002'
30 | 'abc-003'
40 | 'abc-004'
50 | 'abc-005'
现在,col3 值可能会重复(同时由 id 值标识),这是棘手的部分。假设 col1 中缺少的所有值在 col3 中不重复,这就是我更新列的方式:
update DB1.Tab1 as T1
inner join
DB1.Tab3 as T3 ON T3.col7 = T1.col2
inner join
DB2.Tab4 as T4 ON T4.col9 = T3.col6
inner join
DB2.Tab2 as T2 ON T2.col5 = T4.col8
set
T1.col1 = T2.col3
where
T1.col1 is null;
这通常也适用于重复值 - 但我只想在 col3 值不重复时更新 col1,即在这种情况下使用值 abc-2、abc-4、abc-5。这就是我选择单个 col3 值的方式(与更新相关):
select
col3
from
DB2.Tab2 as T2
inner join
DB2.Tab4 as T4 ON T2.col5 = T4.col8
inner join
DB1.Tab3 as T3 ON T4.col9 = T3.col6
inner join
DB1.Tab1 as T1 ON T3.col7 = T1.col2
where
T1.col1 is null
and T1.col2 is not null
group by col3
having count(*) = 1;
问题是:如何仅使用不重复的 col3 值更新 col1 和 col3?
编辑。这几乎可以工作:
update DB1.Tab1 as T1,
(select
col3
from
DB2.Tab2 as T2
inner join DB2.Tab4 as T4 ON T2.col5 = T4.col8
inner join DB1.Tab3 as T3 ON T4.col9 = T3.col6
inner join DB1.Tab1 as T1 ON T3.col7 = T1.col2
where
T1.col1 is null
and T1.col2 is not null
group by col3
having count(*) = 1) as T2d
set
T1.col1 = T2d.col3
where
T1.col1 is null;
但它只使用一个 col3 值更新所有空 col1 值 - 第一个来自 select 查询。我认为 where 子句中缺少某些内容,但我无法制定适当的条件。
【问题讨论】:
标签: mysql database sql-update