sql兩表聯合更新

來源:互聯網
上載者:User

標籤:style   blog   http   strong   io   資料   html   ar   

標籤:sql 聯合更新 資料庫 休閑 職場原創作品,允許轉載,轉載時請務必以超連結形式標明文章 原始出處 、作者資訊和本聲明。否則將追究法律責任。http://yukai.blog.51cto.com/1761494/372585

今天遇到資料庫的一個更新操作.

1個資料庫中有兩個表(其中一個表是從另一個資料庫複寫來的,方法見我以前文章),這兩個表通過公司名稱對應起來,其中一個有稱謂(Mr.,Miss.,Mrs),另一個沒有,將這個表的稱謂匯入到另一個表中:

sql:  update tb_company set tb_company.Salutation1=tb_companyorg.Title from tb_company,tb_companyorg  where tb_company.CompanyName_eng=tb_companyorg.Company_name
此sql語句作用為:將tb_companyorg表的Title(稱謂)匯入到tb_company表的Salutation1(稱謂)欄位中,通過兩表的公司名稱進行對應,一次性匯入了17w+條資料

參考link:http://www.cnblogs.com/ywkpl/archive/2008/03/11/1101276.html

參考內容:

 

Product(pid,name,amount,nowAmount):標識,名稱,已有數量,當前數量
Trade(id,pid,operType,number):標識,產品標識,操作類型(入庫:1,出庫:0),數量

Product表中測試資料:

1 蘋果 100 0
2 桔子  50 0

Trade表中測試資料:

1 1 1 432
2 1 0 50
3 2 1 20
4 2 0 40
5 1 1 30
6 2 0 20


現要求一條SQL語句更新Product表中nowMount值
語句如下:
 

update p set p.nowAmount = p.amount+t.number
from Product as p ,(select pid,sum(case operType when ‘0‘ then number* (-1)  else number end) number 
from Trade group by pid) as t where t.pid=s.pid

或者
 

update p
set p.nowAmount= t.number+p.amount
from Product as p 
inner join (select pid ,sum(case operType when ‘0‘ then number* (-1)  else number end) as number from Trade group by pid) as t
on p.pid=t.pid

兩者一樣執行後Product表:

1 蘋果 100 512
2 桔子 50 10

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.