mysql子查询_笔记之MySQL子查询
子查詢
students(學(xué)生表),scores(成績表)、courses(課程表)
子查詢:在select 語句中,嵌入了另外一個(gè) select 語句, 那么被嵌入的 select 語句稱之為子查詢語句,子查詢分(標(biāo)量子查詢、列子查詢、行子查詢、表子查詢)
標(biāo)量子查詢: 子查詢返回的結(jié)果是一個(gè)數(shù)據(jù)(一行一列)
查詢班級學(xué)生的平均年齡
select avg(age) from students
查詢大于平均年齡的學(xué)生 ,上一句結(jié)果8
select * from students where age>8
select * from students where age>(select avg(age) from students)(這就是標(biāo)量子查詢)
列子查詢: 返回的結(jié)果是一列(一列多行)
下面方法是子查詢
學(xué)生表中查詢18歲的學(xué)生的學(xué)號
select studentNo from students where age=18
成績表中根據(jù)學(xué)號查詢成績
select * from scores where studentNo in ('002','006')
select * from scores where studentNo in (select studentNo from students where age=18)
行子查詢: 返回的結(jié)果是一行(一行多列)
查詢男生中年齡最大的學(xué)生信息
1、select * from students where sex='男' and age=(select max(age) from students)
2、select * from students where (sex,age) = (select sex,age from students where sex='男' order by age desc limit 1)
3、select * from students
where age=(select max(age) from students where sex='男')
表級子查詢: 返回的結(jié)果是多行多列(把某一個(gè)結(jié)果表當(dāng)成一個(gè)原始表來應(yīng)用,實(shí)際上縮小了比對時(shí)間,本來要比對8條數(shù)據(jù)現(xiàn)在只需要比對2條)
查詢語文和數(shù)學(xué)的課程成績
select * from scores s
inner join (select * from courses where name in ('語文','數(shù)學(xué)')) c
on s.courseNo = c.courseNo
內(nèi)連接:select * from courses c
inner join scores s on c.courseNo=s.courseNo
where c.name='語文' or c.name='數(shù)學(xué)'
ps:有時(shí)子查詢不一定比條件查詢、內(nèi)連接方便,實(shí)際上只是在某些情況下子查詢比較便捷而已
總結(jié)
以上是生活随笔為你收集整理的mysql子查询_笔记之MySQL子查询的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 五种常见流媒体协议
- 下一篇: mysql数据库名长可为64字符,MyS