mysql子查询_笔记之MySQL子查询
子查詢
students(學生表),scores(成績表)、courses(課程表)
子查詢:在select 語句中,嵌入了另外一個 select 語句, 那么被嵌入的 select 語句稱之為子查詢語句,子查詢分(標量子查詢、列子查詢、行子查詢、表子查詢)
標量子查詢: 子查詢返回的結果是一個數據(一行一列)
查詢班級學生的平均年齡
select avg(age) from students
查詢大于平均年齡的學生 ,上一句結果8
select * from students where age>8
select * from students where age>(select avg(age) from students)(這就是標量子查詢)
列子查詢: 返回的結果是一列(一列多行)
下面方法是子查詢
學生表中查詢18歲的學生的學號
select studentNo from students where age=18
成績表中根據學號查詢成績
select * from scores where studentNo in ('002','006')
select * from scores where studentNo in (select studentNo from students where age=18)
行子查詢: 返回的結果是一行(一行多列)
查詢男生中年齡最大的學生信息
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='男')
表級子查詢: 返回的結果是多行多列(把某一個結果表當成一個原始表來應用,實際上縮小了比對時間,本來要比對8條數據現在只需要比對2條)
查詢語文和數學的課程成績
select * from scores s
inner join (select * from courses where name in ('語文','數學')) c
on s.courseNo = c.courseNo
內連接:select * from courses c
inner join scores s on c.courseNo=s.courseNo
where c.name='語文' or c.name='數學'
ps:有時子查詢不一定比條件查詢、內連接方便,實際上只是在某些情況下子查詢比較便捷而已
總結
以上是生活随笔為你收集整理的mysql子查询_笔记之MySQL子查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 五种常见流媒体协议
- 下一篇: 【Python】25个好用到爆的一行Py