有没有更有效的方法这样做

时间:2013-05-16 10:47:34

标签: mysql

我想用另外两个表的内容更新一个表的行。是否有更有效的方法,而不是使用2个别名(new_data AS x & y)锁定表。

SET AUTOCOMMIT=0;

START TRANSACTION;

LOCK TABLES
1_products_speech WRITE,
new_data as x WRITE,
new_data as y WRITE;

UPDATE 1_products_speech 
SET 
    v1 = (SELECT 
            data_blob
        FROM
            new_data as x
        WHERE
            id = 1),
    v2 = (SELECT 
            data_blob
        FROM
            new_data as y
        WHERE
            id = 2)
WHERE
    fk_products_id = 1890;

COMMIT;

UNLOCK TABLES;

1 个答案:

答案 0 :(得分:1)

Mysql支持多表更新语句,因此您可以将查询重写为:

UPDATE 1_products_speech 
JOIN new_data x ON id = 1
JOIN new_data y ON id = 2
SET
  v1 = x.data_blob,
  v2 = y.data_blob
WHERE fk_products_id = 1890;

因为与其他表的连接不依赖于主表中的值,所以我怀疑它在性能方面更有效,尽管在编码方面它可能被认为更有效。