简体   繁体   English

左联接后更新行

[英]update rows after left join

I'm looking for a way to update some values in a table if they were used in a left join. 我正在寻找一种方法来更新表中的某些值(如果它们在左联接中使用的话)。

I have two tables: 我有两个表:

table1:
id | name | age | job
1  | john | 31  | 
2  | eric | 25  | 

table2:
id | job | inserted
1  | lawyer | 0
2  | dentist | 1
3  | cop    |  0

Then I run the query: 然后我运行查询:

UPDATE  table1
LEFT JOIN
        table2
ON      table1.id = table2.id
SET     table1.job = `table2.job`
WHERE   table2.inserted = 0

But I want to update the rows from table2 that were used in the update so they have inserted = 1. This for two reasons 1) to speed up the join and 2) so I can check which rows of table2 were not used. 但是我想更新更新中使用的table2中的行,因此它们已插入=1。这有两个原因:1)加快了连接速度; 2)我可以检查未使用table2哪些行。 (The inserts in table2 happen before table1 , but the id s in table2 should always be present in table1 if all cron jobs run okay.) table2的插入发生在table2 table1之前,但如果所有cron作业都运行正常,则table2id始终应存在于table2 table1 。)

You shouldn't be using a LEFT JOIN , since you only want to update rows in table1 that have a matching row in table2 . 您不应该使用LEFT JOIN ,因为您只想更新table1中具有table2匹配行的行。 Try: 尝试:

UPDATE table1 AS t1
JOIN table2 AS t2 ON t1.id = t2.id
SET t1.job = t2.job, t2.inserted = 1
WHERE t2.inserted = 0

DEMO DEMO

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

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