单表查询
查询所有:
select * from t_table1;
使用条件过滤:
- select * from t_table1 where 条件;
- 条件运算符:
- 比较:=,>,<,!=(<>),>=,<=
- 逻辑:is,and,or,not
- 模糊:like, %表示任意多个字符,_表示一个字符
- 范围:in,between a and b
- 排序:order by 字段名 asc 默认升序,可以不加asc,升序为desc select * from t_table1 order by id desc; 可对多个字段排序,order by id,id1,id2
- 分页:limit 10 取前十条数据 limit m,n 从m+1条记录开始取,往后一共取n条数据
- 聚合函数:sum(字段),avg(字段),max(字段),min(字段),count(*) 聚合函数一般和分组一起使用
- 分组:group by 需要注意的是select后的字段应与group by后的字段一致
- group_concat(字段) 分组后获取分组中指定字段的集合,如select name group_concat(id) from t_table1 group by name; 获取name对应的所有id
having 对分组后的数据进行条件过滤
查询对应字段,取别名:
select id as 编号,name as 名字 from t_table1 as t1; as可以省略 select id 编号,name 名字 from t_table1 t1;
去重:
select distinct id from t_table1; 或 select distinct id,name from t_table1; distinct后面跟多个字段时,只有多个字段完全相同时才可以去重
多表查询
- select * from t_table1,t_table2; 两张表数据一一对应组成一张表,查询结果为m*n条
- 内链接:select * from t_table1 t1 inner join t_table2 t2 on t1.id = t2.tid; 相当于取交集,两表都有的才符合条件
- 左连接: select * from t_table1 t1 left join t_table2 t2 on t1.id = t2.id; 此时以左表为准,取所有数据,如果右表没有满足条件的,则取空值
- 右连接:同左连接
自连接:select * from t_table1 t1 inner join t_table1 t2 on t1.x=t2.y; 把同一张表中的不同字段作为条件来进行查询
mysql学习笔记2(查询)
原文:https://www.cnblogs.com/being-a-tester/p/10317633.html