2017-10-31数据库编程sql-day2笔记

来源:互联网 发布:淘宝隐藏优惠券代码 编辑:程序博客网 时间:2024/06/03 23:04
1.逻辑运算符补充
between的用法
select column1,column2....N from 表名 where columnX between 第一个值 and 第二个值;

select * from cus where age between 20 and 30;


sql中逻辑运算符的优先级

级别   操作符
1     `(非)
2    *(乘),/(除),%(取模)
3    + - & ^ | 
4          == > < >= <= <> != !> !<</div>
5          not
6          and
7          all,ant,between,in,like,or,some
8          =(赋值)
注意 sql中可以使用园括号()来控制优先级

二.update 更改
update 表名 set coiumn1 = value1,coiumn2 = values2....N where 条件;
注意: 如果没有where语句将会把表格中所有数据全部更改

三.delete 删除
delete from 表名 where 条件;
注意:没有where会将表中所有数据删除,保留表头信息

四.like 语句
通配符%: 0,1,或更多
通配符_:单一数字或单一字符
select * from 表名 where 列名 like 'XXXX%';
select * from 表名 where 列名 like '_XXXX_';

五.limit 限制
select * from 表名 limit n;
其中,n指返回表中前n条记录
select * from 表名 limit m,n;
其中 m指记录开始的索引号,第一条记录代码是0 n是指从第m条记录开始,取n条
例如:
select * from cus limit 3;
select * from cus limit 3,2;

六.order by排序
ASC 升序
DESC 降序

select 列名 from 表名 order by 列名 ASC;
注意:order by 后面的列名 不必在select语句后出现


七 group by 分组

group by 用来与聚合函数(比如,count总数,sum球和,avg平均值,min最小值,max最大值)联合使用,得到一个列或多个列的结果

语法: 
select column1,column2....N,聚合函数(表达式) from 表名 
where 条件 
group by column1,column2...N 
order by column1,column2...N;

注意:
1.group by之后的列必须出现在select语句之中
2.group by语句必须在where语句之后,order by语句之前
3.因为聚合函数通过作用于一组数据而只返回一个单个值,因此,在select语句中出现的元素要么为一个函数的输入值,要么为group by语句的参数,否则会出错
4.where语句后不能直接跟聚合函数

八.Having 语句:
having语句通常与group by语句联合使用,用来过滤由group by语句返回的记录表
having语句的存在弥补了where语句不能语句和函数使用的不足

语法如下:
select column1,column2....N,聚合函数(表达式) from 表名 
where 条件 
group by column1,column2...N 
having 条件1,条件2....N (聚合函数) 
order by column1,column2....N asc;

九.distinct 不同的
与select一起使用 除去重复项,提取唯一的记录项目

语法: select distinct column1,column2...N
from 表名
where 条件;
例如:
select count(distinct age) from cus;