---
title: "常用的SQL语句"
author: "编程足球"
date: "2011-07-06T23:05:25Z"
tags: []
categories: ["数据库"]
slug: "sql"
draft: false
lastmod: "2011-07-06T23:07:12Z"
id: 1117485
url: "https://lingf.iteye.com/blog/1117485"
---

最近用到关于数据库的查询，突然发现好多都忘记了。晚上就复习下，随便做下笔记。以便以后查询。（超简单的就不写了，写一些经常忘记的。）

<span style="color:red">1. 查询经过计算的值</span>

```java

//   查询姓名和出身年份
select name ， 2011 - age
from student；

```


<span style="color:red">2. 消除重复行   DISTINCT</span>

```java

//    查询有选修了课程的学生学号(一个人可能不止选一门)
select DISTINCT Sno
from SC；

```


<span style="color:red">3. 条件查询</span>
主要有下面几种：
比较：   =,>,<,>=,<=,!=,<>,!>,!<,NOT
范围：   between and， not between and
集合：   in  ，  not in
匹配：   Like， not like
空值 :    is null ， is not null
多重：   and   ，  or  ， not

<span style="color:red">4.in 的基本使用 </span>

```java

//    查询属于  cs ， ma， is 系的学生
select * 
from student 
where Sdept in('cs','ma','is');

```


<span style="color:red">5.like 的使用</span>
一般格式如下

```java

[not] like '<匹配字符串>' [escape '<字符转换符>']

```

% ： 任意长度(可以为0)
_   :   任意单个字符


```java

//   查询DB_Design 课程的课程号 和 学分
select Cno， Ccredit
from Course
where Cname like 'DB\_Design' escape '\'

```


<span style="color:red">6. IS NULL</span>


```java

//  查询选修后没有参加考试(即无分数)学生
select *
from SC
where Grade is null   //  不能用 = 代替 is

```


<span style="color:red">7. ORDER BY</span>
ASC 升序
DESC 降序

```java

//    查询选修3号课程的学生成绩，按照成绩降序排列
select Sno ， Grade
from SC
where Cno = '3'
order by Grade desc；

```

对于空值 升序 最后显示 ， 降序 最先显示

<span style="color:red">8. 聚集函数</span>
Count *       统计
count ( <列名>)     统计一列中值得个数
SUM( <列名>)       统计一列值得总和(该列必须为数值型)
AVG( <列名>)        统计一列中平均值
MAX( <列名>)       统计一列中最大值
MIN( <列名>)        统计一列中最小值


```java

//  统计学生人数
select count (*)
from student

//  查询1号课程的平局值
select AVG(Grade)
from SC
where Cno = '1'

// .............

```

<span style="color:red">9.GROUP BY</span>
GROUP BY 字句将结果按照某一列或多列的值分组，等值的为一组
HAVING  可以对结果进行进一步的筛选

```java

//   查询各个课程号及相应的选课人数
select Cno ， COUNT(Sno)
from SC
GROUP BY Cno;

//    查询选修了3门以上课程的学生学号
select Sno
from SC
GROUP BY Sno
HAVING COUNT(*) > 3

```


以上代码都是本人手动输入。如果有错望指出，
欢迎转载，最好指明出处：
<http://lingf.iteye.com/blog/1117485>
以上例子都是来源于：《数据库系统概论 (第四版)》