简体   繁体   English

更新不匹配的左联接行

[英]Update left join rows that didn't match

Problem: I'd like to update rows that don't match a left join (or another fast solution). 问题:我想更新与左联接不匹配的行(或其他快速解决方案)。 Initial goal: Update records of mytable1 that have state=0 and has either (XOR!) column "a" that matches mytable2, or column "b" that matches mytable2 ("a" and "b" should not both match!). 初始目标:更新状态为= 0且具有(xOR!)与mytable2匹配的列“ a”或与mytable2匹配的列“ b”(“ a”和“ b”不应都匹配!)的mytable1记录。 Set the records of both tables to state=5. 将两个表的记录设置为state = 5。

I tried (and failed): 我尝试了(但失败了):

update mytable1 as t1 
    left join mytable2 as t2 on (t1.a=t2.a and t1.b=t2.b) 
set t1.state=5,t2.state=5 
where t1.state=0 and t2.state=0 and t2.a is null;

As you can see I tried to join all records that match BOTH values, so that I could update records that don't match, also updating the rows that didn't match in mytable2. 如您所见,我试图合并所有两个值都匹配的记录,以便我可以更新不匹配的记录,还可以更新mytable2中不匹配的行。 Rows from mytable1 get updated but not those from table2. 来自mytable1的行将被更新,但不会更新来自table2的行。 I could update the rows that DO match the left join, but that's 99% of the rows which would be a performance hit I think (I did ask this question so I never got to compare ;). 我可以更新与左联接匹配的行,但这是行的99%,我认为这会对性能造成影响(我确实问过这个问题,所以我从来没有进行比较;)。

Thank you for your time. 感谢您的时间。

Something like this should do it: 这样的事情应该做到:

UPDATE `mytable1`
    JOIN `mytable2` ON `mytable1`.`state` = `mytable2`.`state`
        AND
        (
            (`mytable1`.`a` = `mytable2`.`a` AND `mytable1`.`b` != `mytable2`.`b`) OR 
            (`mytable1`.`b` = `mytable2`.`b` AND `mytable`.`a` != `mytable2`.`a`)
        )
SET `mytable1`.`state` = 5, `mytable2`.`state` = 5
WHERE `mytable1`.`state` = 0;

Here's what I came up with: 这是我想出的:

update mytable1 t1 inner join mytable2 t2 on (t1.a=t2.a or t1.b=t2.b or t2.c=t1.c) set t1.state=5,t2.state=5 where((cast(t1.a=t2.a as unsigned integer) + (cast(t1.b=t2.b as unsigned integer) + (cast(t1.c=t2.c as unsigned integer)) <3) and t1.state=0;

Yes, max 2 values could be equal, only 1 should be different. 是的,最多2个值可以相等,只有1个可以不同。

It looks like it works, and it's fast. 看起来可行,而且速度很快。 Any comment? 任何意见?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM