MySQL学习笔记:从一个表update到另外一个表

# ---- 测试数据 ----
# 表1
CREATE TABLE temp_x AS
    SELECT  AS c_id, 1.11 AS c_amount FROM DUAL
UNION ALL
    SELECT  AS c_id, 1.22 AS c_amount FROM DUAL;
# 表2
CREATE TABLE temp_y AS
    SELECT  AS c_id, 1.43 AS c_amount FROM DUAL
UNION ALL
    SELECT  AS c_id, 1.44 AS c_amount FROM DUAL;
# 查询
SELECT * FROM temp_x;
SELECT * FROM temp_y;

# 恢复数据
UPDATE temp_x SET c_amount = 1.11 WHERE c_id = ;
UPDATE temP_x SET c_amount = 1.22 WHERE c_id = ;
# 报错 不可执行
UPDATE temp_x a
    SET a.`c_amount` = b.c_amount
    FROM temp_y b
    WHERE a.`c_id` = b.c_id;
# 还是报错
UPDATE temp_x a
SET a.`c_amount` = b.`c_amount`
FROM temp_x a, temp_y b
WHERE a.`c_id` = b.`c_id`;    <br />

可行的办法:

# 方法一 可行
UPDATE temp_x a, temp_y b
SET a.`c_amount` = b.`c_amount`
WHERE a.`c_id` = b.`c_id`;
# 方法二 可行
UPDATE temp_x a 
    SET a.`c_amount` = (SELECT b.c_amount FROM temp_y b
                WHERE b.`c_id` = a.`c_id`)
# 方法三 可行 方法二加强版
UPDATE temp_x a
SET a.c_amount = (SELECT b.c_amount
            FROM temp_y b
          WHERE b.c_id = a.c_id)
WHERE a.c_id IN (SELECT b.c_id FROM temp_y b);

END2018-05-2917:01:00

相关推荐