大纲
1.基本查询语句
2.指定查询条件
3.注释和sql语句注意事项
4.运算符
5.字符串模糊查询
1.基本查询语句
select
#从学生表查询出全部列
select *
from student;
#为列设置别名
select 姓名 as s_name,性别 as "人类性别"
from student;
#删除重复数据
select distinct 姓名
from student;
#distinct 用在多列之前
select distinct 学号,姓名
from student;
- SQL语句基本规则
—以英文分号结尾
—不区分关键字大小写
—列名不能加单引号
—符号只能写英文符号
2.指定查询条件
#设定查询条件
3.select 姓名,学号
1.from student
2.where 姓名="猴子";
运行顺序
1.from从哪张表中查找数据
2.where查询出符合条件的行
3.从查询出的行中选取出select语句指定的列
3.如何给sql写注释和常见注意事项
—注释有什么用
帮助阅读者更好地理解sql语句,特别是书写复杂sql语句的时候。比如过了一年已经忘记了写过的sql是什么意思,但是看了注释能够快速回忆起来
—注释的种类
——单行注释
-- 查询出全部列
select *
from student;
——多行注释
/*查找姓名是猴子学生的学号*/
select 姓名,学号
from student
where 姓名="猴子"
——sql注意事项
select 姓名,性别
from student;
4.运算符
算术运算符 含义
- 加法
— 减法
× 乘法
÷ 除法
select 学号,成绩,
成绩/100 as "百分比成绩"
from score;
比较运算符 含义
= 相等
>< 不等于
> 大于
>= 大于等于
< 小于
<= 小于等于
select 姓名,性别
from student
where 姓名="猴子";
select 学号,成绩
from score
where 成绩<60;
select 姓名,出生日期
from student
where 出生日期<"1990-01-02"
- 如何查询出null值?
select 教师号,教师姓名
from teacher
where 教师姓名 is null;
select 教师号,教师姓名
from teacher
where 教师姓名 is not null;
逻辑运算符 含义
not 否定某一条件
and 并且
between 范围查询
or 或者
in or的简单写法
#查找出成绩小于60的行
select 学号,成绩
from score
where not 成绩> =60;
select 学号,成绩
from score
where 成绩<60;
#查找出成绩大于60小于90的行
select 学号,成绩
from score
where 成绩>60 and 成绩<90;
#查询条件:性别是男并且姓名是猴子或者马云
select 姓名,性别
from student
where 性别="男"
and (姓名="猴子" or 姓名="马云");
select 姓名,性别
from student
where 姓名 in ("猴子","马云")
#范围查询:between
60<=成绩<=90
select 学号,成绩
from score
where 成绩 between 60 and 90
5.模糊查询
%表示任意字符串
#查询姓猴的学生名单
select *
from student
where 姓名 like "猴%";
#查询姓名中最后一个字是“猴”的学生名单
select *
from student
where 姓名 like "%猴";
#查询姓名中带“猴”的学生名单
select *
from student
where 姓名 like "%猴%";
练习
1.查询学生表
*查询
#查询学生表的两列
select 姓名,性别
from student;
#查询学生表的全部列
select *
from student;
#给列名重命名
select 姓名 as s_name,性别 as "人类性别"
from student;
#删除有重复值的一列
select distinct 姓名
from student;
#删除多列
select distinct 学号,姓名
from student;
如果运行全部语句,选择运行/运行
如果运行已选择的,选择运行/运行已选择的
2.理解sql运行顺序
select 姓名,性别
from student
where 姓名="猴子";
step1:从学生表中查找
from student
step2:找出姓名是猴子的行
where "姓名"="猴子"
step3:从查询出的行中选取出select语句指定的列
select 姓名,性别
统一步骤:
1.select子句最后运行
2.其他子句按照书写顺序运行
3.算术和比较运算符
#添加百分比成绩这一列
select 学号,成绩
成绩/100 as "百分比成绩"
from score;
#找出名字是猴子这一行
select 姓名,性别
from student
where 姓名="猴子";
#找出成绩小于60这一行
select 学号,成绩
from score
where 成绩<60;
#找出出生日期小于1990-01-02
select 姓名,出生日期
from student
where 出生日期<"1990-01-02";
#找出教师姓名是空的一行
select 教师号,教师姓名
from teacher
where 教师姓名 is null;
4.逻辑运算符
#查找出成绩小于60的行
select 学号,成绩
from score
where not 成绩> =60;
select 学号,成绩
from score
where 成绩<60;
#查找出成绩大于60小于90的行
select 学号,成绩
from score
where 成绩>60 and 成绩<90;
#查询条件:性别是男并且姓名是猴子或者马云
select 姓名,性别
from student
where 性别="男"
and (姓名="猴子" or 姓名="马云");
select 姓名,性别
from student
where 姓名 in ("猴子","马云");
#范围查询:between
60<=成绩<=90
select 学号,成绩
from score
where 成绩 between 60 and 90;
5.模糊查询
#查询姓猴的学生名单
select *
from student
where 姓名 like "猴%";
#查询姓名中最后一个字是“猴”的学生名单
select *
from student
where 姓名 like "%猴";
#查询姓名中带“猴”的学生名单
select *
from student
where 姓名 like "%猴%";