MySQL 進階查詢

來源:互聯網
上載者:User

標籤:

進階查詢

1.串連查詢(對列的擴充)

第一種形式
select * from Info,Nation #會形成笛卡爾積

select * from Info,Nation where Info.Nation = Nation.Code #加入篩選條件


select Info.Code,Info.Name,Sex,Nation.Name from Info,Nation where Info.Nation = Nation.Code
#查詢指定列

select Info.Code as ‘代號‘,Info.Name as ‘姓名‘,Sex as ‘性別‘,Nation.Name as ‘民族‘,Birthday as ‘生日‘ from Info,Nation where Info.Nation = Nation.Code
#換表頭

第二種形式:
select * from Info join Nation #join串連,形成笛卡爾積 查詢很慢
select * from Info join Nation on Info.Nation = Nation.Code #join關鍵字

 

2.聯集查詢(對行的擴充)

select * from Info where Nation = ‘n002‘
union #關鍵字
select * from Info where Code = ‘p002‘

 

3.子查詢(無關子查詢) 如果子查詢語句可以單獨拿出來執行,就是無關查詢
在一個sql語句中有兩個子查詢,其中一個a查詢的結果作為另一個b的

select查詢條件,a成為裡層查詢,b為外層查詢或父查詢

查詢民族為‘漢族‘的人員資訊:
select * from Info where Nation = ( select Code from Nation where Name = ‘漢族‘)

查詢民族為 ‘漢族‘ 或者 ‘回族‘ 的人員資訊

select * from Info where Nation in (select Code from Nation where Name = ‘漢族‘ or Name = ‘回族‘)

select * from Info where Nation not in (select Code from Nation where Name = ‘漢族‘ or Name = ‘回族‘)
#in 關鍵字 not in不在表裡

 

4.子查詢(相互關聯的子查詢)

查詢同一系列的 油耗 要比平均油耗低的汽車資訊
子查詢
select avg(oil) from Car where Brand = ‘‘
父查詢
select * from Car where oil<平均油耗

select * from Car a where a.oil < (select avg(b.oil) from Car b where b.Brand = a.Brand)

#b.Brand 是 查詢條件,a.Brand 是 逐條的資訊

MySQL 進階查詢

聯繫我們

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