MySQL自娱—5.DQL语言

DQL(Data Query LANGUAGE),数据查询语言


基础操作

mysql> select distinct community_name from all_house;                      // distinct去重,查询房源表全部小区名
mysql> select distinct concat(group_name,community_name) from all_house;   // concat拼接,区域名小区名拼接
mysql> select distinct concat(group_name,community_name) as 城市区域小区名 from all_house;  // as起别名;as可省略

mysql> select version();                    // 查询版本——函数
mysql> select 100*199 as 结果;              // 用于计算——表达式
mysql> select @@auto_increment_increment;   // 查询自增的步长——变量

# 操作最好先用 `use 库名` 访问到要查询表的库
# 字段加 `` 不是单引号,是着重号
# mysql不区分字符和字符串
# 查询列表可以是:表中的字段,常量值,表达式,函数
# 查询的结果是一个虚拟的表格

 

其他操作

- 查询常量值
| mysql> select 100;
| mysql> select 'smitty';

- 查询表达式
| mysql> select 100*98;
| mysql> select 100/33;          // 取商
| mysql> select 100%33;          // 取余

- 查询函数
| mysql> select version();

- +号的作用
| mysql> select 100+90;     // 操作数都是数值型,则做加法运算
| mysql> select "123"+90;   // 一方是字符,试图转换 如成功 继续加法运算
| mysql> select "john"+90;  // 如果转换失败,则将字符型数值转换为0
| mysql> select null+90;    // 一方为null 则结果为null 

- ifnull函数
| mysql> select ifnull(last_name, 0) as 姓, last_name from info;   // 是Null的数据显示为0

- isnull函数
| mysql> select isnull(id), id from employees;      // 判断是否是null, 返回的是0和1

条件查询

- 按条件表达式筛选
| 有条件运算符称为条件表达式: >  <  =  !=  >=  <=
| != 最好用   <>

- 按逻辑表达式筛选
| 有逻辑运算符称为逻辑表达式:&& || ! and or not
| 作用:用于连接条件表达式
| - &&和and 两个条件都为true,结果true,反之为false
| - ||和or  如果有一个条件为true,结果为true,反之为false
| - !或not  如果连接的条件本身为false,结果为true,反之为false

- 模糊查询 like
| like 配合上 % 或者 _
| % 任意多个字符,包含0个字符
| _ 任意单个字符

- like 示例
| mysql> select * from employees where last_name like "%a%";    // 包含字符a的员工信息
| mysql> select * from employees where last_name like '__e_a';  // 第三个字符为e第五个字符为a的
| mysql> select * from employees where last_name like '__%';    // 第二个字符为下划线的;或者转义了  
| mysql> select * from employees where last_name like '_\_% ';  // 同上,转义写法
| # 推荐用法  like "_a_%" escape "a"  意思是说a之后的_不作为通配符
                
- between and
| mysql> select * from employees where employee_id between 100 and 120;  
| # 等价于,大于等于左边的值,小于等于右边的值,包含临界值;两个数值顺序不能调换

- in
| mysql> select * from employees in (a, b, c);  
| # 不支持通配符

- is null
| mysql> select * from employees is null;
| # = 号不能判断null值
| # 安全等于 <=> 可以判断Null值 也可以判断普通值

排序查询

mysql> select 列 from 表 where order by 排序列 asc(升序)|desc;            // asc可以省略
mysql> select length(name) as 长度 from 表 order by length(name) desc;   // length函数
mysql> select * from 表 order by 列1 asc, 列2 desc;        // 多层次排序

# 总结:
# 1. asc代表升序, desc代表降序, 不写默认升序
# 2. order by子句中可以支持单个字段 多个字段 表达式 函数 别名
# 3. order by子句一般是放在查询语句的最后面,但limit子句除外
posted @ 2022-01-08 01:02  梵高de画笔  阅读(30)  评论(0编辑  收藏  举报