二、SQL简单查询

177 阅读2分钟

本次演示使用三个表,表名与单元格列名如下:
course表:课程号、课程名称、教师号
score表:学号、课程号、成绩
student表:学号、姓名、出生日期、性别
teacher表:教师号、教师姓名

1、SQL基本查询语句

1)select...from

select <列名1>,<列名2>  -- select子句
from <表名>  -- from子句

实例:

select 姓名,性别
from student

image.png

2)*号的作用

-- 可以用星号(*)查询出全部列
select *
from  Student

image.png

3)as重设列名

-- 使用as 为列设定别名
select  姓名 as s_name,性别 as ’人类性别’
from  Student

image.png

4) distinct删除重复数据

-- 使用distinct删除重复数据   
select  distinct  姓名  -- 用在单列之前:该列有重复值时去重
from  Student

image.png

5)where指定查询条件

-- 用where指定查询条件
select 姓名,学号
from student
where 姓名='猴子'  -- 选取姓名列为‘猴子’的行

注:语句运行顺序为:先运行from,再到where,最后才到select

image.png

6) --单行注释 /* */ 多行注释

/*
查找姓名是猴子的学生的选号
*/
select 姓名,学号
from student
where 姓名='猴子'  -- 选取姓名列为‘猴子’的行

7)算数运算符(加减乘除)

SELECT 学号,成绩,成绩/100 as 百分比成绩 
from score

image.png

8)比较运算符

包括:相等(=) 不等于(<>)大于(>)大于等于(>=) 小于( < ) 小于等于(<=)

SELECT 学号,成绩
from score
where 成绩< 80

9)逻辑运算符 no/and/between/or/in

no:否定某一条件
and:并且
between:范围查询
or:或者
in: or的另一种写法

SELECT 学号,成绩
from score
where not 成绩>=80  -- 相当于查询成绩<80

image.png

in与 or的用法

-- or 或者
SELECT 学号,成绩
FROM score
WHERE 成绩<80 or 成绩>90
-- in是or的简便写法
SELECT 姓名,性别
FROM student
WHERE 姓名 in('小李','猴子')

10)查询null值的方法

SELECT 教师号,教师姓名
FROM teacher
where 教师姓名 is  null

image.png

SELECT 教师号,教师姓名
FROM teacher
where 教师姓名 is not null

image.png

11)like进行模糊查询

使用like进行模糊查询
%表示任意字符串 _(1个下划线)表示任意1个字符

-- 查询姓'猴'的学生名单
SELECT *
FROM student
where 姓名 like '猴%'
/*查询姓名中最后一个字是'猴'的学生名单*/
SELECT*
FROM	student
WHERE 姓名 like '%猴'
-- 查询姓'王'的学生名单,并且姓名是3个字的
SELECT *
FROM student
WHERE 姓名 like '王__'  -- 两个下划线