MySQL查询操作
SELECT select_expr [,select_expr,...] [
FROM tb_name
[WHERE 条件判断]
[GROUP BY {
col_name | postion} [ASC | DESC], ...]
[HAVING WHERE 条件判断]
[ORDER BY {
col_name|expr|postion} [ASC | DESC], ...]
[ LIMIT {
[offset,]rowcount | row_count OFFSET offset}]
]
select distinct *
from 表名
where ....
group by ... having ...
order by ...
limit start,count
执行顺序为:
- from 表名
- where …
- group by …
- select distinct *
- having …
- order by …
- limit start,count
MySQL查询操作 | 命令行代码 |
---|---|
select查询所有字段、指定字段的数据 | select * from students; select name,age from students; |
消除重复行命令distinct | select distinct gender from students; |
as给字段、表起别名 | select s.name as '姓名',s.age as '年龄' from students as s; |
条件查询where后跟比较运算符、逻辑运算符的用法 | > 、< 、 >= 、 <= 、 = 、 !=、 and 、or、 not |
条件查询中的模糊查询like和范围查询in | name like '%杰' % : 代表任意个字符 _ : 代表一个字符 |
判断is null和非空判断is not null | select * from students where height is (not) null; |
查询中使用order by排序 | 放在 from、where、group by之后 order by 列1 asc ,列2 desc; desc: 降序 asc:升序,默认 |
常用到的聚合函数count、max、min、sum、avg | count(*)\count(列):总数 max(列): 最大值 min(列): 最小值 sum(列) : 求和 avg(列) :求平均 |
分组查询group by + group_concat(字段名)/聚合函数/having | group by: 分组 group_concat: 拼接字符串,拼接字段名 聚合函数: 最大,最小平均,计数,求和 having: 对分组后的结果集进一步筛选 注意: select 列 中只能存放分组函数(比如聚合函数),或是出现在group by子句中的分组标签 where: 对源数据做条件筛选, 不能接聚合函数 having: 是对分组之后的数据做进一步的筛选操作, 有having就一定有group by, 有 group by 不一定有having,接聚合函数 |
分页查询获取部分行的命令limit | limit [start],count 1. 放在查询语句的最后 2. start=(page-1)*count |
连接查询inner/left/right join | inner join on :内连接(结果仅包含符合连接条件的两表中的行) left join on : 左连接(完全显示左表所有的行,如果左表中某行 在右表中没有匹配的行,则右表该行显示NULL) right join on : 右连接(与左连接相反) |
子查询的方法 | 查询中嵌套查询,三种:标量子查询: 子查询的结果为一个值(一行一列) 列子查询: 子查询的结果为一个列(一列多行) 表子查询: 子查询的结果为一个表(多行多列) |
MySQL 查询
创建数据库、数据表
初始化数据
-
1 .创建data_demo数据库
create database data_demo charset=utf8; use data_demo;
-
2 .创建classes表(id,name)
create table classes(id int unsigned not null primary key auto_increment,name varchar(30) not null);
-
3 . 创建students表(id,name,age,height,gender,cls_id,is_delete)
create table students( id int unsigned primary key auto_increment not null, name varchar(20) default '', age tinyint unsigned default 0, height decimal(5,2), gender enum('男','女','中性','保密') default '保密', cls_id int