1.基础查询
语法
select 查询的列 from 表名;
查询列表: 表中的字段、常量值、表达式、函数
查询的结果是一个虚拟的表格
查询所有字段:
select * from account;
查询单个字段:
select name from account;
查询多个字段
select name,money from account;
查询常量值
查询表达式
查询函数(方法)
起别名 as 关键字 可以省略
便于理解、如果查询多张表要查询的字段有重名的情况,使用别名可以区分开来
去重 distinct关键字 或者 group by 字段名
查询
员工表中的所有部门编号
select distinct money from account;
select money from account group by money;
+ 号的作用
运算符 两个字段为数值类型 ,如果一方为字符型的数值,他会尝试转换为数值类型,转换成功就做加法运算,失败则将字符串转换为0,只要其中一方为 null则结果为null;
员工姓和员工名 连接成一个字段
select id+money as qianren from account;
拼接函数 concat(str1,str2....)
select concat(id,money) as qianren from account;
判断为空函数
ifnull(参数1,参数2) 参数1 要判断的值,参数2 默认值, 如果参数1是null设置的一个默认值
条件查询
select 查询列表 from 表名 where 筛选条件;
条件运算符
# > < = != <> <= >=
select * from account WHERE money>1000;
逻辑表达式
&& || !
and or not
select * from account WHERE money>1000 and money<=3000;
select * from account WHERE money>1000 or money<=3000;
select * from account WHERE not(money>1000 and money<=3000) or money=2000;
模糊查询
like
# c开始
select * from account where name like 'c%';
# c 开始 或者包含c或者c结尾
select * from account where name like '%c%';
# c结尾
select * from account where name like '%c';
# 第二个字符是c
select * from account where name like '_c%';
# 第一个字符是c第三个字是c
select * from account where name like 'c_c%';
between and
# id在 1-4之间 包含1和4
select * from account where id BETWEEN 1 AND 4;
in
# id= 1或者2或者4之间
select * from account where id in(1,2,4);
is null
# id为null的
select * from account where id IS NULL;
# id不等于null的
select * from account where id IS not NULL;
<=>
# id等于null的 安全等于
select * from account where id <=> null;
排序查询
# ASC 升序 DESC 降序
select 数据列表 from 表民 order by 表列名 ASC或者DESC;
# 按id降序
select * from account ORDER BY id DESC;
# 按 name 排序 name 一样 按money 牌
select * from account ORDER BY `name` DESC,money DESC;