例表:
一、普通查詢
無條件:
select * from student;
/* "*" 的意思是打印表中所有字段,等同
select id,name,age,sex,grade_id,class_id
from student;
*/
有條件:
select id,name
from student
where age = 18;
/* "where" 的意思是進行對字段篩選 */
二、去重查詢(distinct)
/*
distinct 去重查詢,顧名思義就是去掉重複數據
*/
select distinct age from student;
三、排序查詢
order by(升序ASC、降序DESC)
/*
order by 排序:升序(ASC)、降序(DESC)。
*/
select distinct id,name,age from student
order by age ASC;
select distinct id,name,age from student
order by age DESC;
四、分組查詢
group by(分組)
/*
SUM()求和
*/
select id,name,SUM(score)
from course
group by id;
五、多表查詢
等值查詢:
select name,course_name,score
from student,course
where student.id = course.stu_id
and age <= 20
and score < 60;
六、連接查詢
外連接:
1、左連接查詢(左表數據全部存在)
select name,course_name,score
from ( select id,name
from student
where age<=20
)a
left join
(
select stu_id,score
from course
where score<60
)b
on a.id = b.stu_id
where score is not null;
2、右連接查詢(保留右表滿足條件數據,左表補NULL)
select name,course_name,score
from ( select id,name
from student
where age<=20
)a
right join
(
select stu_id,score
from course
where score<60
)b
on a.id = b.stu_id
where name is not null;
3、全連接查詢(保留左右滿足條件的數據)
select name,course_name,score
from ( select id,name
from student
where age<=20
)a
full join
(
select stu_id,score
from course
where score<60
)b
on a.id = b.stu_id
where name is not null
and score is not null;
內連接:(只有完全匹配纔會保留)
select name,course_name,score
from ( select id,name
from student
where age<=20
)a
inner join
(
select stu_id,score
from course
where score<60
)b
on a.id = b.stu_id;
七、聯合查詢(union,union all)
聯合結果集不必受被聯合的多個結果集之間的關係限制,不過使用UNION仍然有兩個基本的原則需要遵守:
1.每個結果集必須有相同的列數;
2.每個結果集的列必須類型相容,即結果集的每個對應列的數據類型必須相同或者能夠轉換爲同一種數據類型。
聯合查詢Union又有Union和Union All兩種方式,下面分別說下他們的用法以及區別:
select stu_id,course_name,score
from course
where score<60
Union --union聯合查詢:有去重功能
select stu_id,course_name,score
from course
where score>=90;
select stu_id,course_name,score
from course
where score<80
Union all --union all聯合查詢:將所有數據都存入結果集
select stu_id,course_name,score
from course
where score>=70;
union有去重複的功能,union all沒有去重複功能,所以union的效率會低點,如果查詢的結果集沒有要求去重或者聯合表中不存在重複數據 建議使用union all操作。