1. 程式人生 > >MySQL中如何用一個表中的欄位更新另一個表中欄位

MySQL中如何用一個表中的欄位更新另一個表中欄位

1,修改1列

update student s, city c
set s.city_name = c.name
where s.city_code = c.code;

2,修改多個列

update  a,  b
set a.title=b.title, a.name=b.name
where a.id=b.id
  • 子查詢
update student s set city_name = (select name from city where code = s.city_code);

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

oracle查詢報這個錯誤:single-row subquery returns more than one row怎麼解決? 

資料庫按照你的條件查詢有多個重複的資料。

例如:

UPDATE "SYS_ROLE" A

SET A ."DEPT_ID" = (

    SELECT

        c."id"

    FROM

        "his_department_info" c

    WHERE

        c."dept_name" = A ."ROLE_NAME"

如果以上sql語句報single-row subquery returns more than one row的錯誤,說明 c表”dept_name” 和A 表.”ROLE_NAME” 的這兩個欄位 資料重複

 

2、 寫法輕鬆,更新效率高:

update table1 
set field1=table2.field1,
field2=table2.field2
from table2
where table1.id=table2.id