mysql update join sql語句總結

2021-07-23 21:52:22 字數 1559 閱讀 1651

首先注意的是你用的是mysql還是sqlserver

此處是針對mysql 進行join進行更新的

update sales a join goods b on a.id=b.id set a.cat_id=b.cat_id  ;

假定我們有兩張表,一張表為product表存放產品資訊,其中有產品**列price;另外一張表是productprice表,我們要將productprice表中的**欄位price更新為price表中**欄位的80%。

在mysql中我們有幾種手段可以做到這一點,一種是update table1 t1, table2 ts ...的方式:

update product p

,productprice pp

set pp

.price =pp

.price

*0.8

where p

.productid =pp

.productid

and p

.datecreated

<

'2004-01-01'

另外一種方法是使用inner join然後更新:

update product p

inner join productprice pp

on p

.productid =pp

.productid

set pp

.price =pp

.price

*0.8

where p

.datecreated

<

'2004-01-01'

另外我們也可以使用left outer join來做多表update,比方說如果productprice表中沒有產品**記錄的話,將product表的isdeleted欄位置為1,如下sql語句:

update product p

left join productprice pp

on p

.productid =pp

.productid

set p

.deleted =1

where pp

.productid is

null

另外,上面的幾個例子都是兩張表之間做關聯,但是只更新一張表中的記錄,其實是可以同時更新兩張表的,如下sql:

update product p

inner join productprice pp

on p

.productid =pp

.productid

set pp

.price =pp

.price

*0.8,p

.dateupdate

=curdate

()where p

.datecreated

<

'2004-01-01'

兩張表做關聯,更新了productprice表的price欄位

參考 

Oracle SQL delete刪除語句總結

delete語句總結 delete sql用途 用於刪除表中的某行或整個資料表中的資料 語法 delete from where 注意事項 如果有外來鍵關聯,則刪除資料之前,需先刪除外來鍵關聯資料 delete應用例項 刪除部門編號為 2bsb 的部門資訊 delete from gem file ...

MySQL和SQL Server基本語句總結(三)

這一節主要總結一下在php中使用mysql進行資料庫的程式設計。使用mysql 常用函式 1.mysql connect 伺服器名稱,使用者名稱,密碼 判斷連線 錯誤則使用 mysql error 函式 2.mysql select db 選擇資料庫 3.mysql query 執行語句 返回結果集...

matlab程式設計之迴圈語句與條件語句的總和使用

功能 根據控制台輸入的數字來判斷它的大小 disp 數字比大小.for i 1 10 d input 請輸入乙個數 if d 100 if d 10 disp 這是乙個小於10的數字 elseif d 20 disp 這個是10 20之間的數值 elseif d 50 disp 這是乙個20 50之...