一、當用乙個表中的資料來更新另外乙個表中的資料時(兩張表要有關聯):
1. update t1 set t1.c2 = t2.c2
from t2 where t1.c1 = t2.c1
2. update t1 set t1.c2 = t2.c2
from t1 inner join t2 on t1.c1 = t2.c1
二、from子句中指定的表的別名不能作為set column_name子句中被修改的字段的限定符使用
update titles
set t.ytd_sales = t.ytd_sales + s.qty
from titles t, sales s
where t.title_id = s.title_id
and s.ord_date = (select max(sales.ord_date) from sales)
若要使上例合法,請從列名中刪除別名 t 或使用本身的表名。
update titles
set ytd_sales = t.ytd_sales + s.qty
from titles t, sales s
where t.title_id = s.title_id
and s.ord_date = (select max(sales.ord_date) from sales)
更新一列:
update mytab a set name=(select b.name from goal b where b.id=a.id)
where exists (select 1 from goal b where b.id=a.id);
更新多列:
update mytab a
set (name,address)=(select b.name,b.address
from goal b
where b.id=a.id)
where exists (select 1
from goal b
where b.id=a.id )
特別是要注意exists後面的語句:)這會讓目標行不至於為null
更新update多個關聯表的sql寫法:
update customers a
set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)update 超過2個值
update customers a
set (city_name,customer_type)=(select b.city_name,b.customer_type
from tmp_cust_city b
where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)
--另一種修改形式update so_item set so_item.quantity=quantity-(select sum(quantity) from @salerule_itemlist as rule_item where rule_item.productsysno=so_item.productsysno)
from @so_itemlist as so_item
where so_item.productsysno in (select productsysno from @salerule_itemlist)
更新update多個關聯表的sql寫法:
update customers a
set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)update 超過2個值
update customers a
set (city_name,customer_type)=(select b.city_name,b.customer_type
from tmp_cust_city b
where b.customer_id=a.customer_id)
where exists (select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)
Sql 基礎語法join以及多張表join
sql join 用於根據兩個或多個表中的列之間的關係,從這些表中查詢資料。有時為了得到完整的結果,我們需要從兩個或更多的表中獲取結果。我們就需要執行 join。資料庫中的錶可通過鍵將彼此聯絡起來。主鍵 primary key 是乙個列,在這個列中的每一行的值都是唯一的。在表中,每個主鍵的值都是唯一...
SQL基礎 修改資料 UPDATE
update 更新資料庫表中的記錄 基本語法 update 表set 欄位1 值1,欄位2 值2,where.select from sudents where id 1 查詢結果 例項要求 更新students表id 1的記錄的name和score這兩個字段 update students set...
sql用逗號連線多張表對應哪個join?
四種join的區別已老生常談 那麼問題來了,還有一種常見的寫法是將錶用逗號隔開,那這個又是怎麼連線的呢。先看這兩張表。使用逗號隔開的方法來連線表 select from employee,department where employee.departmentid department.depart...