SQL多表查詢

來源:互聯網
上載者:User

 

情況一:

我們現在兩個表,一個學生Student表,一個性別Gender表。Student : id name gender 。Gender :: key value

 

有如下值:

Student :

001 xy 1

002 xyy 1

003 小紅 0

 

Gender

0 女

1 男

2 其他

 

那麼我們先看一個表 Student,我要尋找性別為男的學生

select  id,name,gender from Student where gender = '1';

 

那我們多表查詢,找到男學生,性別顯示不再是0,1,2 而是漢字

select s.id,s.name,g,value

from Student s,Gender g

where s.gender = '1'

and g.key = s.gender (正確)// 兩條記錄

 

看到了嗎?我們不僅要寫s.gender = '1' 還要寫g.key = s.gender。也就是不僅要判斷值等於什麼,而且要寫出關聯欄位的相等關係。

 

select s.id,s.name,g,value

from Student s,Gender g

where s.gender = '1' (錯誤)// 2*3 = 6條記錄 2個男學生*3個性別表記錄(笛卡兒積)

 

 

 

select s.id,s.name,g,value

from Student s,Gender g

whereg.key = s.gender (錯誤)// 3條記錄,3個學生,不分性別

 

 

情況二:

 

我們現在兩個表,一個學生Student表,一個參數CS表。Student : id name gender , status。CS :: key value name

 

有如下值:

Student :

001 xy 1      0

002 xy 1      0

003 xh 0      0

 

CS

gender   0    女

gender   1    男

gender   2   其他

status     0   在校

status     1   離校

 

我現在要 取出姓名,性別,在校狀態。

select s.name,xb.mc,zt.mc

from  Student s,

(select key value name from CS where key = 'gender') xb,

(select key value name from CS where key = 'status') zt

where s.gender = xb.value

and s.status = zt.value;

 

這就不能向情況一中一樣簡單的兩表關聯了。你不可能CS.key又等於gender又等於status吧。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.