【SQL】SQL中的資料查詢語句匯總

來源:互聯網
上載者:User
文章目錄
  • where條件運算式
  • 子查詢
  • 串連語句(應用於多表查詢)
where條件運算式--統計函數
Select count(1) from student;
--like模糊查詢

--統計班上姓張的人數

select count(*) from student where realName like '張%';

--統計班上張姓兩個字的人數

select count(*) from student where realName like '張_';

--統計班上杭州籍的學生人數

select count(*) from student where home like '%杭州%';

--查詢班上每位學生的年齡

select realName,year(now())-year(birthday) as age from student;

--查詢90年出生的學生

select realName from student where year(birthday)>='1990';

--查詢1987-1990年出生的學生

select realName from student where year(birthday)<='1990' and year(birthday)>=’1987’;select * from student where year(birthday) between '1987' and '1990';

--查詢班上男女生人數

select sex,count(*) from student group by sex;

--in子句查詢班上B或O型血的學生

select realName,blood from student where blood in('B','O');  
子查詢

子查詢也可稱之為巢狀查詢,有些時候,一次查詢不能解決問題,需要多次查詢。

按子查詢返回的記錄行數區分,可分為單行子查詢和多行子查詢;

select * from emp where sal>(       select sal from emp where ename='ALLEN‘ or ename =‘KING’) 

上例是找出比allen工資高的所有員工

A.子查詢一般先於主語句的運行
B.必須有( ),表示一個整體
C.習慣上把子查詢放在條件的右邊

多行子查詢:some,any,all 

串連語句(應用於多表查詢)

包括:內聯,外聯(左外連和右外聯)

內聯(inner join):把兩張表相匹配的行查詢出來。
--查詢每個學生的各科成績,顯示“姓名”“課程名”“分數”三列

select a.realname,c.courseName,b.score from stu_student as a inner join stu_score as b on a.sid=b.sid inner join stu_course c on b.cid=c.cid

還有一種方法,不採用inner join:

select a.realname,c.courseName,b.score from student a,score b,course c where a.sid=b.sid and c.cid=b.cid

外聯分左外聯和右外聯:
Left outer join:查詢兩邊表的匹配記錄,且將左表的不匹配記錄也查詢出來。

Right outer join:等上,將右表不匹配記錄也查詢出來。

select a.realname,b.score from stu_student as a left outer join stu_score as b on a.sid=b.sid

聯繫我們

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