Data Query Language,数据查询语言,常用于 select
1. 基础查询
语法:select 查询列表 from 表名;
特点:
- 查询列表可以是:表中的字段、常量值、表达式、函数
- 查询的结果是:一个虚拟的表格
# 查询单个字段
select field1 from tableName;
# 查询多个字段
select field1,field2 from tableName;
# 查询使所有字段
select * from tableName;
# 查询常量值
select 100;
select "xiaowei";
# 查询表达式
select 100+200;
# 查询函数
select VERSION();
# 起别名 as 或 空格
select field1 as "aliasName" from tableName;
select field1 "aliasName" from tableName;
# 去重 distinct
select distinct field1 from tableName;
# +:只能做加法运算
# 数值+数值=数值
# 数值+字符,字符先转换成数值,成功继续运算,不成功转换成0再运算
# 数值+null=null
# concat(字符1,字符2,。。):拼接字符
# ifnull(参数1,参数2):参数1为null,返回参数2,否则返回参数1的值
# isnull(参数1):参数1为null,返回1,否则返回0
2.条件查询
语法:select 查询列表 from 表名 where 筛选条件;
特点:
筛选条件分类
- 条件表达式:> < = != <> >= <=
- 逻辑表达式:&& || ! and or not
- 模糊查询:like /between...and / in /is null
- like 经常和通配符一起使用,%:代表0到多个字符,-:代表一个字符
- escape 转义
# like
select * from tableName where name like '_$_%' escape '$';
# between and,两边都包含
select * from tableName where age between 18 and 30;
# is null/is not null
# = null 不能使用,可以使用安全等于代替 <=> null
select * from tableName where name is null;
select * from tableName where name is not null;
3.排序查询
语法:select 查询列表 from 表名 [where 筛选条件] order by 排序列表 [asc|desc];
特点:
- asc代表升序,desc代表降序,默认是asc
- order by 子句中可以是:单个字段、多个字段、表达式、函数、别名
- order by 子句一般放在查询语句的最后面,limit子句除外
- 排序的字段有重复值时,注意分页会产生重复数据问题(百度一下)