如何優雅的使用SQL資料庫表之間的連線?

2021-09-27 10:10:11 字數 3520 閱讀 9747

一:首先,我們要理解資料庫的表連線方式有幾種。

二:下面乙個乙個介紹他們的使用

先建立兩個表,乙個是學生表,另外乙個是成績表;

學生表:student

stdno

stdname

stdage

std***

stdclass

001小白17女

1002

小李18女2

003小蔣18男

1004

小陳15女2

成績表:score

scoreid

stdno

stdscore

1004872

00292

3001905

00598

1.內連線(inner join)

內連線是指連線結果僅包含符合連線條件的行,參與連線的兩個表都應該符合連線條件。

內連線查詢語法:select * from studentinner joinscoreonstudent.stdno = score.stdno

查詢結果:

stdno

stdname

stdage

std***

stdclass

scoreid

stdno

stdscore

001小白17女

1300190

002小李18女

2200292

004小陳15女

2100487

2.外連線

外連線的連線結果不僅包含符合連線條件的行同時也包含自身不符合條件的行。分為左外連線、右外連線和全外連線。

(1)左外連線(left join):左邊表資料的行全部保留,右邊表保留符合連線條件的行。

左外連線查詢語法:select student.*,score.* from studentleft joinscoreonstudent.stdno = score.stdno

查詢結果:

stdno

stdname

stdage

std***

stdclass

scoreid

stdno

stdscore

001小白17女

1300190

002小李18女

2200292

003小蔣18男

1null

null

null

004小陳15女

2100487

(2)右外連線(right join):右邊表資料的行全部保留,左邊表保留符合連線條件的行。

右外連線查詢語法:select student.*,score.* from studentright joinscoreonstudent.stdno = score.stdno

查詢結果:

stdno

stdname

stdage

std***

stdclass

scoreid

stdno

stdscore

001小白17女

1300190

002小李18女

2200292

004小陳15女

2100487

null

null

null

null

null

5005

98(3)全外連線(full join):全外連線是在等值連線的基礎上將左表和右表的未匹配資料都加上。

全外連線查詢語法:select student.*,score.* from studentfull joinscoreonstudent.stdno = score.stdno

查詢結果:

stdno

stdname

stdage

std***

stdclass

scoreid

stdno

stdscore

001小白17女

1300190

002小李18女

2200292

003小蔣18男

1null

null

null

004小陳15女

2100487

null

null

null

null

null

5005

983.交叉連線(cross join)

交叉連線返回左表中的所有行,左表中的每一行與右表中的所有行組合。交叉聯接也稱作笛卡爾積。

在此例中,student表有4行,score表有4行。笛卡爾積返回4*4=16行記錄。查詢語句沒有on條件,可以用where限制。

交叉連線查詢語法:select student.*,score.* from studentcross joinscore

查詢結果:

stdno

stdname

stdage

std***

stdclass

scoreid

stdno

stdscore

001小白17女

1100487

001小白17女

1200290

001小白17女

1300192

001小白17女

1500598

002小李18女

2100487

002小李18女

2200290

002小李18女

2300192

002小李18女

2500598

003小蔣18男

1100487

003小蔣18男

1200290

003小蔣18男

1300192

003小蔣18男

1500598

004小陳15女

2100487

004小陳15女

2200290

004小陳15女

2300192

004小陳15女

2500598

資料庫雜談之 如何優雅的進行表結構設計

資料庫表結構設計作為後端軟體開發不可或缺的一環,是每個後端工程師都會經歷的過程。筆者也多次經歷過這樣的過程,也嘗試過多種不同的設計方案,也從一些優秀的框架中學到不少,但並沒有發現相關的文章對其進行總結。所以本文嘗試把筆者看到的 學到的總結下來,希望對閱讀本文的讀者有所啟發。表結構設計主要有兩個目的,...

如何寫資料庫表的SQL ?

現有a b c三個表 主鍵都是snum,現要實現刪除a表中某個記錄 比如snum為1的記錄 如何級聯刪除b c表中snum為1的記錄?如果b,c表的snum是參照a的snum,那麼b,c兩張表要加入下面的級聯sql,不然在是無法刪除a,b,c表的記錄的 alter table b add const...

使用SQL語句建立資料庫和資料庫表

內容如下 建立資料庫 建立資料庫表 1.建立資料庫的語句 建立資料庫,需要建立資料庫的資料檔案和日誌檔案 其中一些語句含義如下 語句代表含義 name 邏輯檔名 filename 物理檔名 size 檔案初始大小 maxsize 檔案最大長度 filegrowth 檔案增長幅度 其中邏輯檔名不需要加...