一般查询格式:
SELECT [ALL | DISTINCT] <目标表达式> [,<目标表达式>] ...
FROM <表名或视图名> [,<表名或视图名>] ...
[WHERE <条件表达式>]
[GROUP BY <列名1> [HAVING <条件表达式>]]
[ORDER BY <列名2> [ASC | DESC]];
单表查询
1.选择表中若干列
SELECT Sno,Sname ...
SELECT * ...
SELECT 2004 - Sage,LOWER(Sdept),Sname NAME ... /*输出经过计算的表达式的值,输出小写值,
用NAME代替原列标题Sname*/
2.选择表中的若干组
SELECT DISTINCT Sage ... /*结果中消除取值重复的行,缺省为ALL*/
查询满足条件的元组
(1)比较大小
=,>,<,>=,<=,!= <>,!>,!<,NOT+比较运算符
SELECT Sname FROM Student WHERE Sage < 20;
(2)确定范围
SELECT * FROM Student WHERE Sage BETWEEN 20 AND 23;
... NOT BETWEEN 20 AND 23;
(3)确定集合
SELECT * FROM Student WHERE Sage IN (20,23,16);
... NOT IN (20,23,16);
(4)字符匹配
SELECT * FROM Student WHERE Sname LIKE 'lulu'; /*等同于 = 'lulu'*/
LIKE 'lu%'; /*匹配字符串,%为任意长度任意字符串*/
LIKE 'lul_'; /*匹配字符串,_为任意单个字符*/
(5)空值查询
... WHERE Sage IS NULL; /*IS不可用=代替*/
... IS NOT NULL;
(6)多重条件查询
... WHERE Sage = 20 AND Sname = 'lulu'; /*且关系*/
... WHERE Sage = 20 OR Sage = 23 OR Sage = 16; /*或关系,IN实际为多个OR缩写*/
AND优先级高于OR,可用括号改变其优先级别
聚集函数
SELECT COUNT (DISTINCT Sage) ... /*统计某一总数,去除重复项*/
COUNT * ...
COUNT (0) ...
SELECT SUM (Sage)... /*计算某列值得总和*/
SELECT AVG (Sage)... /*计算某列平均值*/
SELECT MAX (Sage)... /*计算某列最大值*/
SELECT MIN (Sage)... /*计算某列最小值*/
GROUP BY 子句
SELECT Cno,COUNT (Sno) FROM SC GROUP BY Cno;
SELECT Sno FROM SC GROUP BY Sno HAVING COUNT (*) > 3; /*WHERE作用于基本表视图,
HAVING作用于组,从组中选择满足条件的组*/
SELECT country,count(0) FROM info GROUP BY country HAVING count(0) > 10 ORDER BY count(0) DESC
查询结果按某一列或多列的值分组,值相等的为一组
分组后,聚集函数作用于每一组,每一组都有一个值
ORDER BY 子句
...ORDER BY Sage ASC | DESC; /*ASC升序,DESC降序*/
连接查询
1.等值与非等值连接查询
SELECT Student.*,SC.* FROM Student,SC WHERE Student.Sno = SC.Sno;
/*当连接运算符为=时,为等值连接,使用其他链接运算符为非等值连接
自然连接:等值连接中把目标中重复的属性列去掉
为了避免混淆,属性前加表名前缀,如该列唯一,也可不写*/
2.自身连接
SELECT FIRST.Cno,SECOND.Cpno FROM Course FIRST,Course SECOND WHERE FIRST.Cpno = SECOND.Cno;
/*为同一个表Course取2个别名,自身连接操作*/
3.外连接
SELECT Student.Sno,Sname,Ssex,Sage,Sdept,Cno,Grade FROM Student LEFT OUT JOIN SC ON
(Student.Sno = SC.Sno);
/*此处使用左外连接,
也可以使用USING去掉结果中重复值:
FROM Student LEFT OUT JOIN SC USING (Sno);
*/
4.复合条件连接
SELECT Student.Sno,Sname FROM Student,SC WHERE Student.Sno = SC.Sno AND SC.Cno = '2' AND ...;
嵌套查询
SELECT Sname FROM Student WHERE Sno IN
(SELECT Sno FROM SC WHERE Cno = '2');
1.带有IN的子查询
可用=代替IN
2.带有比较运算符的子查询
SELECT Sno,Cno FROM SC x WHERE Grade >=
(SELECT AVG(Grade) FROM SC y WHERE y.Sno = x.Sno);
3.带有ANY(SOME),ALL的子查询
ANY:查询结果中的某一个值
ALL:查询结果中的任何一个值
> ANY > ALL
< ANY < ALL
>= ANY >= ALL
<= ANY <= ALL
= ANY = ALL(通常无实际意义)
!= ANY != ALL
4.带有EXISTS的子查询
SELECT Sname FROM Student WHERE EXISTS
(SELECT * FROM SC WHERE Sno = Student.Sno AND Cno = '1');
/*查询所有选修了1号课程的学生姓名
带有EXISTS的子查询不返回任何数据,只产生逻辑true,false
EXISTS:存在,子查询结果,外层WHERE返回true,否则返回false
NOT EXISTS:不存在,子查询结果,WHERE返回true,否则返回false*/
集合查询
SELECT Sno FROM SC WHERE Cno = '1' UNION SELECT Sno FROM SC WHERE Cno = '2' ;
/*UNION:并操作,合并多个查询结果,去掉重复元素,如想保留重复使用UNION ALL
INTERSECT:交操作
EXCEPT:差操作*/