具有明显Join的MySQL Update

时间:2015-01-23 07:37:32

标签: mysql join sql-update

我有两张桌子:

CREATE TABLE `tmp1` (
    `c1` VARCHAR(50) NULL DEFAULT NULL,
    `c2` VARCHAR(50) NULL DEFAULT NULL
);

CREATE TABLE `tmp2` (
    `c1` VARCHAR(50) NULL DEFAULT NULL,
    `c2` VARCHAR(50) NULL DEFAULT NULL
);

c2是主键。 对于tmp1我有这样的值:

|| 1 || val1 ||
|| 2 || val2 ||
|| 2 || val3 ||

for tmp2:

|| 1 || val11 ||
|| 2 || val22 ||
|| 2 || val33 ||
|| 2 || val44 ||

我需要通过加入c1字段来更新tmp2以接收如下结果:

|| 1 || val1 ||
|| 2 || val2 ||
|| 2 || val3 ||
|| 2 || val44 ||

当我使用常规内连接时,我会收到错误的结果:

|| 1 || val1 ||
|| 2 || val2 ||
|| 2 || *val2* ||
|| 2 || *val2* ||

我需要像这样加入更新:

|| 1 || val1 ||  ->(by c1)  || 1 || val11 ||
|| 2 || val2 ||  ->(by c1)  || 2 || val22 ||
|| 2 || val3 ||  ->(by c1)  || 2 || val33 ||

或者像这样(我想也许更真实)

|| 1 || val1 ||  ->(by c1)  || 1 || val11 ||
|| 2 || val2 ||  ->(by c1)  || 2 || val22 ||

所以在第二种情况下,我认为我需要将cmp2分组为c1,将tmp组分组为c1,然后只更新该组中的一行。

此选择返回我需要更新的内容:

select tmp1.c2, tmp2.c2 from tmp1
inner join tmp2 on tmp1.c1 = tmp2.c1 
group by tmp2.c1

|| val1 || val11 ||
|| val2 || val22 ||

1 个答案:

答案 0 :(得分:0)

我通过此查询解决了我的问题:

UPDATE tmp2 as up
JOIN (select ij.c2 as x, src.c2 as y from tmp1 as src
inner join tmp2 as ij on src.c1 = ij.c1 
group by src.c1) as sel ON up.c2 = sel.x
SET up.c2 = y