聯表查詢的更新

2022-04-08 09:23:51 字數 1999 閱讀 2752

背景:

之前寫過一篇關於資料庫聯表查詢的部落格《再看資料庫——(6)連線》,主要講了連線的型別,以及如何使用連線進行多表查詢。本篇部落格就是在這基礎上延伸而來的。首先,我們先來看乙個聯表查詢的例子。

use testunion

--員工集合

create table staffunion(id int primary key,name varchar(10) not null,comment varchar(30),remark int)

--員工表

create table staff(id int primary key,personname varchar(10) not null,staffunionid int,comment varchar(30),remark int)

--工作計畫表

create table staffplan(id int primary key,staffid int ,planname varchar(10) not null,plancontent varchar(60),remark int)

注:三個表中沒有新增外來鍵約束,考慮到插入刪除資料的方便。

插入幾條簡單的資料:

insert into staffunion values (1,'test1','員工集合一',1);

insert into staffunion values (2,'test2','員工集合二',1);

insert into staffunion values (3,'test3','員工集合三',1);

insert into staff values (1,'張三',1,'無',1);

insert into staff values (2,'李四',1,'無',1);

insert into staff values (3,'王五',2,'無',1);

insert into staff values (4,'李明',2,'無',1);

insert into staffplan values(1,1,'編制計畫','結合年度資訊,編制計畫',1);

insert into staffplan values(2,1,'搭建環境','搭建環境,計畫五個小時',1);

insert into staffplan values(3,1,'編制計畫','結合年度資訊,編制計畫',0);

要求:將員工集合一種的張三對應的編制計畫改為融資計畫,並且是有效資料,即remark=1。

相應的sql語句為:

update staffplan set staffplan.planname='融資計畫' from staffunion

inner join staff on staff.staffunionid=staffunion.id

inner join staffplan on staffplan.staffid=staff.id where staffplan.id=1

and staffplan.remark=1

結果顯示:

staffplan表

如果不使用這種方法,那麼我們先進行聯表查詢。

select staffplan.id,staffplan.planname,staffplan.plancontent,staffplan.remark from staffplan inner join staff on staff.id=staffplan.staffid

inner join staffunion on staffunion.id=staff.staffunionid where staffplan.planname='編制計畫'and staffplan.remark='1'

查到這條資料後,再進行更新。

update staffplan set staffplan.planname='融資計畫' where staffplan.planname='編制計畫'and staffplan.remark='1'

對比分析:

使用連表查詢再更新需要兩個sql語句來完成,而且當資料量比較大的時候,很容易出錯。

關於聯表更新

例項sql update tblnmdevice t1 set t1.keystr select t2.displayname from tblbusinesssys t2 join tblbusinessdeviceunion t3 on t2.tbluuid t3.businessid wher...

zf聯表查詢

zf支援聯表查詢,並且會經常遇到聯表查詢,具體 寫法如下 select this select select from this name,array id name select distinct select joinleft jobname,jobname.enterprise id this...

sql聯表查詢

比如 all list 這個表,是包含所有資料的,我們要把整個資料的某些字段查詢出來顯示在列表上 select from all list select 現在我要檢視一條資料,需要根據表 user list 的乙個字段內容,去檢視另外乙個表 info list 的內容 select dept nam...