mysql 連線查詢

2022-09-12 19:54:14 字數 2927 閱讀 2214

表a記錄如下:

aid        anum

1            a20050111

2            a20050112

3            a20050113

4            a20050114

5            a20050115

表b記錄如下:

bid                bname

1                  2006032401

2       2006032402

3      2006032403

4      2006032404

8      2006032408

1.left join(左聯接)

sql語句如下:

select * from a

left join b

on a.aid =b.bid

結果如下:

aid    anum      bid    bname

1    a20050111    1      2006032401

2    a20050112    2      2006032402

3    a20050113    3      2006032403

4    a20050114    4      2006032404

5    a20050115   null    null

結果說明:

left join是以a表的記錄為基礎的,a可以看成左表,b可以看成右表,left join是以左表為準的.

換句話說,左表(a)的記錄將會全部表示出來,而右表(b)只會顯示符合搜尋條件的記錄(例子中為: a.aid = b.bid).

b表記錄不足的地方均為null.

2.right join(右聯接)

sql語句如下:

select * from a

right joing b

on a.aid = b.bid

結果如下:

aid    anum    bid    bname

1    a20050111    1    2006032401

2    a20050112    2    2006032402

3   a20050113    3    2006032403

4    a20050114    4    2006032404

null    null    8    2006032408

(所影響的行數為 5 行)

結果說明:

仔細觀察一下,就會發現,和left join的結果剛好相反,這次是以右表(b)為基礎的,a表不足的地方用null填充.

3.inner join(相等聯接或內聯接)

sql語句如下:

select * from a

inner join b

on a.aid =b.bid

等同於以下sql句:

select *

from a,b

where a.aid = b.bid

結果如下:

aid    anum    bid    bname

1    a20050111    1    2006032401

2    a20050112    2    2006032402

3    a20050113    3    2006032403

4    a20050114    4    2006032404

結果說明:

很明顯,這裡只顯示出了 a.aid = b.bid的記錄.這說明inner join並不以誰為基礎,它只顯示符合條件的記錄.

left join操作用於在任何的 from 子句中,

組合**表的記錄。使用 left join 運算來建立乙個左邊外部聯接。左邊外部聯接將包含了從第乙個(左邊)開始的兩個表中的全部記錄,即

使在第二個(右邊)表中並沒有相符值的記錄。

語法:from table1 left join table2 on table1.field1 compopr table2.field2

說明:table1, table2引數用於指定要將記錄組合的表的名稱。

field1, field2引數指定被聯接的字段的名稱。且這些字段必須有相同的資料型別及包含相同型別的資料,但它們不需要有相同的

名稱。

compopr引數指定關係比較運算子:"=", "<", ">", "<=", ">=" 或 "<>"。

如果在inner join操作中要聯接包含memo 資料型別或 ole object 資料型別資料的字段,將會發生錯誤。

mysql連線查詢例項 MySQL連線查詢例項詳解

建立表suppliers create table suppliers s id int not null auto increment,s name char 50 not null,s city char 50 null,s zip char 10 null,s call char 50 not...

mysql連線查詢例項 MySQL連線查詢例項詳解

建立表suppliers create table suppliers s id int not null auto increment,s name char 50 not null,s city char 50 null,s zip char 10 null,s call char 50 not...

mysql連線查詢on MySQL連線查詢例項詳解

建立表suppliers create table suppliers s id int not null auto increment,s name char 50 not null,s city char 50 null,s zip char 10 null,s call char 50 not...