多表查詢
- 語法
select 列名列表 from 表名列表 where - 笛卡爾積
有兩個集合A,B,取這兩個集合的所有組成情況
要完成多表查詢,需要消除無用的數(shù)據(jù) - 多表查詢消除無用數(shù)據(jù)的分類
內連接查詢
①隱式內連接
select * from 表1,表2 where 表名.列名1= 表名.列名2;
select * from 表1 t1,表2 t2 where t1.列名 = t2.列名;
②顯示內連接
語法:select 字段列表 from 表名1 inner join 表名2 on 條件;
演示:
select * from student 【inner】 join class on student.cid = class.id;
select * from student join class on student.cid = class.id;
注意:
①從哪些表中查詢數(shù)據(jù)
②條件是什么
③查詢哪些字段外連接查詢
①左外連接:查詢的是左表所有數(shù)據(jù)以及交集部分。
select 字段列表 from 表1 left 【outer】 join 表2 on 條件;
②右外連接:查詢的是右表所有數(shù)據(jù)及交集部分。
select 字段列表 from 表1 right 【outer】join 表2 on 條件;子查詢:查詢中嵌套查詢,嵌套的查詢是子查詢
select * from 表名 where 列名=(select MAX(列名) from 表名);
子查詢
- 子查詢的結果是單行單列的:
子查詢作為條件,使用運算符與之進行比較:>,<,<>,=,
select * from student where 列名 >(select AVG(列名) from result ); - 子查詢的結果是多行單列的:
子查詢作為條件,使用運算符in進行判斷
select * from studen where 列名 in (select 列名 from where 列名=值 OR 列名=值); - 子查詢的結果是多行多列的:
子查詢可以作為一張?zhí)摂M表
select * from 表1 t1,(select * from 表2 where 列名 > 值)t2 where t1.列名 = t.列名