mysql帶條件查詢,聯表查詢

來源:互聯網
上載者:User

標籤:gre   欄位名   操作   均值   分數   並且   group   nbsp   學生   

---恢複內容開始---

1,用於設定所select出來的資料是否允許出現重複行(完全相同的資料行)

all:允許出現——預設不寫就是All(允許的)。

distinct:不允許出現——就是所謂的“消除重複行”

 

2,where:條件

 

3,group by:分組依據 後面加表的欄位名,通常只進行一個欄位的分組

mysql表查詢文法形式:select [all | distinct] 欄位名或運算式 from 表名 [where] [group by] [having] [order by] [limit];

練習題:共有下面四張表    學生表:student  教師表:teacher  課程表:course 成績表:score

 

1,查詢Score表中至少有5名學生選修的並以3開頭的課程的平均分數

--動作表score,以cno分組並且cno是以3開頭,取出各個cno的總數,及與cno對應的degree的平均值

select count(cno),avg(degree) from score where cno like ‘3%‘ group by cno;

 

 

--從虛擬表中找到cno總數大於5的

select * from

(select count(cno) a,avg(degree) b from score where cno like ‘3%‘ group by cno) c

where a>5;

 

2,查詢所有學生的Sno、Cname和Degree列

--找到student的sno
 select sno from student;


 --找到score 的sno,degree,cno
 select sno,degree,cno from score;


 --找到course的cno
 select cno,cname from course;


 --組成新表cno sno degree
 select a.cno,b.sno,b.sname,a.degree from (select sno,degree,cno from score) a  join (select sno,sname from student) b on a.sno=b.sno;


 --組成有cname cno sn degree sname的表
 select d.cname,e.cno,e.sno,e.degree,e.sname
 from
   (select a.cno,b.sno,b.sname,a.degree from (select sno,degree,cno from score) a  join (select sno,sname from student) b on a.sno=b.sno) as e 
  join 
  (select cname,cno from course) as d
  on d.cno=e.cno;

 

3,查詢“95033”班學生的平均分

--從student取sno class,條件是class是95033的

select sno,class from student where class=‘95033‘;

 

--取出score中sno degree

select sno,degree from score;

 

--將上面兩張表組成一張,取degree的平均值

select avg(degree) from

(select sno,class from student where class=‘95033‘) a

join

(select sno,degree from score) b

on a.sno=b.sno;

 

4,查詢選修“3-105”課程的成績高於“109”號同學成績的所有同學的記錄

--將109號的成績取出

select degree from score where sno=‘109‘ and cno=‘3-105‘;

 

-- 得出最終表

select * from score

where

degree>(select degree from score where sno=‘109‘ and cno=‘3-105‘)

and cno=‘3-105‘;

 

5,查詢和學號為108的同學同年出生的所有學生的Sno、Sname和Sbirthday列

--找到student中sno為108 的Sbirthday
select year(sbirthday) from student where sno=‘108‘;


-- 得出最終表
select sno,sname,sbirthday from student

where

year(sbirthday)=(select year(sbirthday) from student where sno=‘108‘);

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.