第3.6课 上课 SQL介绍, Select语句深入介绍

3_6

SQL深入介绍

 Select语句深入介绍

  定义列名的别名

-- 别名

 

select id as '用户 编号', t_name 用户名称, t_salary as 月薪 from e_user;

 

注意:

可以省略 as 关键字

如果别名中使用特殊字符,或者是强制大小写敏感,或有空格时,都可以通过为别名添加引号实现。

 

  其他运算符

   算术表达式

-- 算数运算符

 

1.对数值型数据列、变量、常量,可以使用算数操作符创建表达式(+ -* /)。

2.对日期型数据列、变量、常量,可以使用部分算数操作符创建表达式(+ -)。

例如:

select now() + 10;

3.运算符不仅可以在列和常量之间进行运算,也可以在多列之间进行运算。

 

例如:

 

 

select 1 + 1 as 加法;

 

select (1 + 2) * 3

 

select id as '用户 编号', t_name as 用户名称, t_salary as 月薪, t_salary*12 as 年薪 from e_user;

-- date_format() 对时间类型进行格式化的函数

select date_format(t_birthday, '%Y-%m-%d') from e_user;

-- 表示 日加 10

select date_format(t_birthday+10, '%Y-%m-%d') from e_user;

 

   比较运算符

SELECT * FROM e_user WHERE id >2 AND id < 5;

 

    between运算符:匹配在两个值之间的数据

-- between 运算符

select * from e_user where t_salary between 800 and 900;

 

 

 

    in运算符:匹配列表中的值

-- in 运算符 匹配列表中的值

select * from e_user where t_name in ('admin', 'dave');

 

-- not in 运算符 过滤列表中的值

select * from e_user where t_name not in ('admin', 'dave');

 

 

    like运算符:匹配一个字符模式

使用LIKE运算符执行模糊查询:

(%) 可表示零或多个字符

( _ ) 可表示一个字符

 

例如:

 

select * from e_user where t_name like '%d%';

 

select * from e_user where t_name like '_d%';

 

 

    is null运算符:是空值

-- is null 运算符:判断为空

-- is not null 运算符:判断不为空

 

select * from e_user where t_birthday is null;

 

select * from e_user where t_birthday is not null;

 

   逻辑运算符

    AND:逻辑与

需要所有条件都是满足条件。

 

-- and运算符:逻辑与

select * from e_user where id > 4 and t_salary > 850;

 

 

    OR:逻辑或

只要多个条件满足其中一个就可以。

 

-- or运算符:逻辑或

 

select * from e_user where id > 4 or t_salary > 850;

 

 

    NOT:逻辑非

-- not运算符:逻辑非(取反)

 

select * from e_user where id not in (1,2,3);

 

select * from e_user where not(id >= 4 and t_salary > 700);

 

 

  运算符的优先级

运算符的优先级如下表:

 

注意:使用圆括号()可以改变运算符的优先级。

  结果集进行排序:Order By子句

1.查询语句执行的查询结果,数据是按插入顺序排列。但实际中大多数情况下,需要按某列的值大小排序排列;

 

2.按某列排序采用:order by 列名[asc|desc], 列名[asc|desc], …;

 

3.设定排序列的时候可采用“列名”或者“列的别名”;

 

4.如果按多列排序,每列的asc,desc必须单独设定;

 

例如:

-- order排序(asc代表升序,desc代表降序 asc是默认值,不写排序就表示升序)

select * from e_user order by id asc;

select * from e_user order by id desc;

 

-- 对多列进行排序

select * from e_user order by t_birthday asc, t_salary asc;

 

-- 也可以对列的别名进行排序

select *, t_salary*12 as 年收入 from e_user order by 年收入 asc;

posted on 2018-01-31 22:48  東風★破  阅读(166)  评论(0)    收藏  举报

导航