我正在寻找一种方法来更新表中的某些值(如果在左联接中使用了它们)。
我有两个表:
table1:
id | name | age | job
1 | john | 31 |
2 | eric | 25 |
table2:
id | job | inserted
1 | lawyer | 0
2 | dentist | 1
3 | cop | 0
然后我运行查询:
UPDATE table1
LEFT JOIN
table2
ON table1.id = table2.id
SET table1.job = `table2.job`
WHERE table2.inserted = 0
但是我想从更新中更新
table2
中使用的行,以便它们已插入=1。这有两个原因:1)加快了连接速度; 2)我可以检查table2
的哪些行没有用过的。 (table2
中的插入发生在table1
之前,但如果所有cron作业都运行正常,则id
中的table2
始终应出现在table1
中。) 最佳答案
您不应该使用LEFT JOIN
,因为您只想更新table1
中在table2
中具有匹配行的行。尝试:
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
关于mysql - 左联接后更新行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30719299/