# 一、SELECT查询

## 1.选择表中的若干列

### （1）查询经过计算的值

SELECT子句<目标表达式>不仅可以是表中的属性列也可以是表达式

``````SELECT Sname,2014-Sage
FROM Student;
``````

<目标表达式>不仅可以是算术表达式还可以是字符串常量、函数等。

### （2）改变查询结果列标题

``````SELECT Sname,'Year of Birth: ',2014-Sage,LOWER(Sdept)
FROM Student;
``````

``````SELECT Sname NAME,'Year of Birth: ' BIRTH,2014-Sage BIRTHDAY,LOWER(Sdept) DEPARTMENT
FROM Student;
``````

## 2.选择表中若干元组

### （1）查询满足条件的元组

①比较大小

``````SELECT Sname
FROM Student
WHERE Sdept='CS';
``````

``````SELECT Sname, Sage
FROM   Student
WHERE  Sage < 20;
``````

``````SELECT Sno
FROM  SC
``````

``````SELECT DISTINCT Sno
FROM  SC
``````

②确定范围

``````SELECT Sname,Sdept,Sage
FROM Student
WHERE Sage BETWEEN 20 AND 23;
``````

``````SELECT Sname, Sdept, Sage
FROM   Student
WHERE  Sage NOT BETWEEN 20 AND 23;
``````

③确定集合

``````SELECT Sname,Ssex
FROM Student
WHERE Sdept IN('CS','MA','IS');
SELECT * FROM Student//和全表对比
``````

``````SELECT Sname, Ssex
FROM Student
WHERE Sdept NOT IN ('IS','MA','CS')
``````

④字符匹配

``````[NOT] LIKE ‘< 匹配串>’ [ESCAPE ‘ <换 换

``````

< 匹配串>可以是一个完整的字符串 可以是一个完整的字符串 ，也可以含有通配符 也可以含有通配符%和 和 _
（1）%代表 任意长度 （长度可以为 长度可以为0）的字符串

（2）_代表任意单个字符 。

``````SELECT *
FROM Student
WHERE Sno LIKE '201215121';
``````

``````SELECT *
FROM Student
WHERE Sno = '201215121';
``````

``````SELECT Sname,Sno,Ssex
FROM Student WHERE Sname LIKE '刘%'
``````

Student 表中插入

``````SELECT Sname
FROM Student
WHERE Sname LIKE ' 欧阳_ ';
``````

``````SELECT Sname ，Sno
FROM Student
WHERE Sname LIKE '_ 阳%';
``````

``````SELECT Sname, Sno, Ssex
FROM Student
WHERE Sname NOT LIKE ' 刘%';
``````

``````SELECT Cno,Ccredit
FROM Course
WHERE Cname LIKE 'DB\_Design'ESCAPE'\';
SELECT * FROM Course
``````

``````SELECT *
FROM Course
WHERE Cname LIKE 'DB\_%i_ _' ESCAPE '\ ' ;//和全表对比
``````

ESCAPE ’ ＼’ 表示“ 表示“ ＼” 为换码字符
⑥多重条件查询

``````SELECT Sname
FROM Student
WHERE Sdept= 'CS' AND Sage<20;
``````

``````SELECT Sname, Ssex
FROM Student
WHERE Sdept= ' CS' OR Sdept= ' MA' OR Sdept= 'IS
``````

## ORDER BY子句

``````SELECT *
FROM Student
ORDER BY Sdept, Sage DESC;
``````

## 4.聚集函数：

（1）统计元组个数 COUNT(*)
（2） 统计一列中值的个数 COUNT([DISTINCT|ALL] < 列名>)
（3） 计算一列值的总和 SUM([DISTINCT|ALL] < 列名>)
（4） 计算一列值的平均值 AVG([DISTINCT|ALL] < 列名>)
（5） 求一列中的最大值MAX([DISTINCT|ALL] < 列名>)
（6） 求一列中的最小值MIN([DISTINCT|ALL] < 列名>)

``````SELECT COUNT(*)
FROM Student;
``````

``````SELECT COUNT(DISTINCT Sno)
FROM SC;
``````

``````SELECT COUNT(Grade)
FROM SC
WHERE Cno=1;
SELECT * FROM SC//和全表做对比
``````

``````SELECT MAX(Grade)
FROM SC
WHERE Cno='1';
``````

``````SELECT SUM(Ccredit)
FROM SC,Course
WHERE Sno='201215012' AND SC.Cno=Course.Cno;
``````

## 5.GROUP BY子句分组： 子句分组：

GROUP BY子句将查询结果按一列或多列的值分组

``````SELECT Cno,COUNT(Sno)
FROM SC
GROUP BY Cno;
``````

``````SELECT Sno
FROM SC
GROUP BY Sno
HAVING COUNT(*) >3;
``````