使用具有中间表的另一个数据库中的另一个表的列的一部分数据更新列

时间:2017-07-21 08:18:38

标签: mysql database sql-update

我在数据库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值更新col3和col3?

EDIT。这几乎有效:

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子句中缺少某些东西,但我无法制定适当的条件。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。这个问题非常复杂,但经过深思熟虑之后答案很简单。

我的update语句几乎起作用,在select语句和where子句中缺少附加条件。

update DB1.Tab1 as T1,
    (select 
        col3, T1.col2 as T1c2
    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
        and T1.col2 = T1c2;

解决方案归结为从要更新的表中选择另一列(T1.col2),特别是应更新T1.col1的值,然后将每个T1.col2与先前选择的值进行比较。 / p>

然而,我背后的机制并不清楚,特别是为什么没有这个编辑的update语句会更新只有一个值的所有字段,所以评论仍然受到赞赏。