子查詢合併表

2021-04-01 06:48:12 字數 1630 閱讀 4440

這種方法適用於2個表之間沒有欄位有聯絡,只是按已排列的順序合在一起,下面的方法是不用臨時錶用子查詢實現的方法,該方法不適用於處理大量行。它適用於處理幾百行。對於大型表,一定要使用索引以避免進行大範圍的搜尋。

create  table tb1

(id int identity(1,1) primary key clustered, 

l_name varchar(10))

gocreate  table tb2

(l_id char(3) primary key clustered, 

f_name varchar(10))

--tb1中的資料

id          l_name    

----------- ----------

1           aaa

2           bbb

3           ccc

4           ddd

5           eee

6           fff

7           ggg

8           hhh

9           kkk

--tb2中的資料

l_id f_name    

---- ----------

afd  dfsg1

cbn  gsdg2

cgb  kddf3

dlk  fgjn4

ery  bfhfhx5

fdh  dsdfas6

gjf  dfh7

lft  cfghsh8

snf  dgjhdg9

--合併程式

select id,l_name,l_id,f_name

from (select rank=count(*),a.id,a.l_name from tb1 a join tb1 b on a.id>=b.id group by a.id,a.l_name  ) a1

join (select rank=count(*),a.l_id,a.f_name from tb2 a join tb2 b on a.l_id>=b.l_id group by a.l_id,a.f_name ) a2

on a1.rank=a2.rank

--結果

id          l_name     l_id f_name    

----------- ---------- ---- ----------

1           aaa        afd  dfsg1

2           bbb        cbn  gsdg2

3           ccc        cgb  kddf3

4           ddd        dlk  fgjn4

5           eee        ery  bfhfhx5

6           fff        fdh  dsdfas6

7           ggg        gjf  dfh7

8           hhh        lft  cfghsh8

9           kkk        snf  dgjhdg9

MySQL中合併查詢資料記錄與子查詢

1 帶有關鍵字union的合併操作select from table name1 union select from table name2 執行結果成功顯示合併後的資料記錄,同時去掉了重複資料記錄,使新關係裡沒有任何重複的資料記錄 2 帶有關鍵字union all的合併操作select from ...

使用子查詢建立表

使用子查詢建立表 create table myemp as select from emp create table myemp as select from emp where deptno 10 create table myemp as select from emp 1 2 新增字段 al...

子查詢和連線表

有如下兩張表 部門表和教師表 1 查詢出招生部門所有男老師姓名 子查詢放在where語句中 select tname,deptno from teacher where gender 男 and deptno in select deptno from dept where dname 招生部 se...