我在MySQL中有这个Update语句,它使用select语句更新多个列。
UPDATE TableA
SET ColumnA =
(
SELECT TableB.ColumnA
FROM TableB
WHERE (TableB.ColumnX = 0 AND TableB.id = TableA.fk_id)
)
,ColumnB =
(
SELECT TableB.ColumnB
FROM TableB
WHERE (TableB.ColumnX = 0 AND TableB.id = TableA.fk_id)
)
,ColumnC =
(
SELECT TableB.ColumnC
FROM TableB
WHERE (TableB.ColumnX = 0 AND TableB.id = TableA.fk_id)
)
它工作正常,易于理解。但是,它违反了DRY(不要重复自己)的原则。 WHERE子句重复。它在代码审查练习中看起来不太好。如何以不违反DRY原则的方式重写此MySQL语句?
答案 0 :(得分:2)
UPDATE TableA a INNER JOIN TableB b
ON b.ColumnX = 0 AND b.id = a.fk_id
SET a.ColumnA = b.ColumnA, a.ColumnB = b.ColumnB, a.ColumnC = b.ColumnC;
MySQL更新语法允许组合多个表:http://dev.mysql.com/doc/refman/5.0/en/update.html