sql server中如何連接表更新數據
假設a,b兩表有外鍵關聯,想要從b表中取出相應字段的值更新a表字段,可以有如下幾種寫法:
update a set a.name=b.name from a,b where a.id=b.id
update a inner join b on a.id=b.id set a.name=b.name where ...
update table1 set a.name = b.name from table1 a inner join table2 b on a.id =b
二:
表hotel中有id,hotel_city。
表hotel_room中有id,hotel_id,其中hotel_id與表hotel中的id對應。
表hotel_room_price中有room_id,price,price_year_month,其中room_id與hotel_room中的id對應。其余各項數據之間沒有關聯。
現在要求更新表hotel_room_price中的price字段,符合的條件是room_id對應的hotel_city是744,且price_year_month是'20114'。
SQL語句:
update hotel_room_price set price = 0 from hotel_room_price a,hotel_room b,hotel c where a.room_id = b.id and b.hotel_id = c.id and c.hotel_city = 744 and a.price_year_month = '20114'
重點看紅色的部分。from后跟的是需要聯立的三個表。用where a.room_id = b.id and b.hotel_id = c.id來將三個表當中需要對應的字段聯立起來。and c.hotel_city = 744 and a.price_year_month = '20114'則是最后指定的兩個條件。
運行無錯誤。