工作生活

mysql查询

2019-07-02  本文已影响0人  xiaohan_zhang
创建数据库
-- 创建数据库
create database python_test_1 charset=utf8;

-- 使用数据库
use python_test_1;

-- students表
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 unsigned default 0,
    is_delete bit default 0
);

-- classes表
create table classes (
    id int unsigned auto_increment primary key not null,
    name varchar(30) not null
);
准备数据
-- 向students表中插入数据
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭于晏',29,185.00,1,1,0),
(0,'刘德华',59,175.00,1,2,1),
(0,'黄蓉',38,160.00,2,1,0),
(0,'凤姐',28,150.00,4,2,1),
(0,'王祖贤',18,172.00,2,1,1),
(0,'周杰伦',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'刘亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'静香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周杰',34,176.00,2,5,0);

-- 向classes表中插入数据
insert into classes values (0, "python_01期"), (0, "python_02期");
去重

过滤查询结果中的重复数据,distinct *表示去除完全相同的数据,distance age表示去除年龄相同的数据。
select distinct 列1,... from 表名;
select distinct class from students;
select distinct class, gender from students;

条件

使用where子句对表中的数据筛选,结果为true的行会出现在结果集中
select * from 表名 where 条件;
select * from students where id=1;
where后面支持多种运算符,进行条件的处理
-- 比较运算符
-- 逻辑运算符
-- 模糊查询
-- 范围查询
-- 空判断

等于: =
大于: >
大于等于: >=
小于: <
小于等于: <=
不等于: != 或 <>

查询没被删除的学生
select * from students where is_delete=0;

and
or
not

select * from students where id > 3 and gender=0;
select * from students where id > 3 or gender=0;
select * from students where not age > 20;

like
%表示任意多个任意字符
_表示一个任意字符

// 查询姓黄的学生
select * from students where name like '黄%';
// 查询姓黄并且“名”是一个字的学生
select * from students where name like '黄_';
// 查询姓黄或叫靖的学生
select * from students where name like '黄%' or name like '%靖';
// 查询名字只有两个字的学生
select * from students where name like '__';

rlike 正则

// 查询以周开头的名字
select * from students where name rlike '^周.%';
  1. in表示在一个非连续的范围内
// 查询编号是1或3或8的学生
select * from students where id in(1,3,8);
  1. between ... and ...表示在一个连续的范围内
// 查询编号为3至8的学生
select * from students where id between 3 and 8;
// 查询编号是3至8的男生
select * from students where (id between 3 and 8) and gender=1;
  1. not between ... and ...表示不在一个连续的范围内
// 查询编号不在3至8之间的学生
select * from students where id not between 3 and 8;
  1. 判空 is null
    注意:null与''是不同的
// 查询没有填写身高的学生
select * from students where height is null;
  1. 判非空is not null
// 查询填写了身高的学生
select * from students where height is not null;
排序

select * from 表名 order by 列1 asc|desc,列2 asc|desc,...

将行数据按照列1进行排序,如果某些行列1的值相同时,则按照列2排序,以此类推。
默认按照列值从小到大排列(asc)

// 查询未删除男生信息,按学号降序
select * from students where gender=1 and is_delete=0 order by id desc;
// 查询未删除学生信息,按名称升序
select * from students where is_delete=0 order by name;
// 显示所有的学生信息,先按照年龄从大-->小排序,当年龄相同时 按照身高从高-->矮排序
select * from students order by age desc,height desc;
// 获取年龄最大的同学的信息
select * from students order by age desc limit 1;
聚合函数
// 查询学生总数
select count(*) from students;
select count(*) as 总数 from students;
select count(distinct class) from students;  # class去重后个数
// 查询女生的身高最大值
select max(height) from students where gender=2;
// 查询未删除的学生最小身高
select min(height) from students where is_delete=0;
// 查询男生的总年龄
select sum(age) from students where gender=1;
// 平均年龄
select sum(age)/count(*) as 平均年龄 from students where gender=1;
// 查询未删除女生的年龄平均值
select avg(age) from students where is_delete=0 and gender=2;
// 计算所有人平均年龄 保留两位小数
select round(avg(age), 2) from students;
// 计算男性平均身高,保留两位小数
select round(avg(height), 2) from students where gender=1;

注:为了保证存储数据准确性,可以在存储时X100,减小存储小数造成误差。

分组
select gender from students group by gender;
+--------+
| gender |
+--------+
| 男     |
| 女     |
| 中性   |
| 保密   |
+--------+

注:一般group by不单独使用。

select gender,group_concat(name) from students group by gender;

+--------+-----------------------------------------------------------+
| gender | group_concat(name)                                        |
+--------+-----------------------------------------------------------+
| 男     | 彭于晏,刘德华,周杰伦,程坤,郭靖                                 |
| 女     | 小明,小月月,黄蓉,王祖贤,刘亦菲,静香,周杰                        |
| 中性   | 金星                                                       |
| 保密   | 凤姐                                                       |
+--------+-----------------------------------------------------------+

select gender,group_concat(name,"_",age) from students group by gender;
分别统计性别为男/女的人年龄平均值
select gender,avg(age) from students group by gender;
+--------+----------+
| gender | avg(age) |
+--------+----------+
| 男     |  32.6000 |
| 女     |  23.2857 |
| 中性   |  33.0000 |
| 保密   |  28.0000 |
+--------+----------+
select gender,count(*) from students group by gender having count(*)>2;
+--------+----------+
| gender | count(*) |
+--------+----------+
| 男     |        5 |
| 女     |        7 |
+--------+----------+
select gender,count(*) from students group by gender with rollup;
+--------+----------+
| gender | count(*) |
+--------+----------+
| 男     |        5 |
| 女     |        7 |
| 中性   |        1 |
| 保密   |        1 |
| NULL   |       14 |
+--------+----------+

select gender,group_concat(age) from students group by gender with rollup;
+--------+-------------------------------------------+
| gender | group_concat(age)                         |
+--------+-------------------------------------------+
| 男     | 29,59,36,27,12                            |
| 女     | 18,18,38,18,25,12,34                      |
| 中性   | 33                                        |
| 保密   | 28                                        |
| NULL   | 29,59,36,27,12,18,18,38,18,25,12,34,33,28 |
+--------+-------------------------------------------+
获取部分行(分页)

从start开始,获取count条数据
select * from 表名 limit start,count

// 查询前3行男生信息
select * from students where gender=1 limit 3;
select * from students where gender=1 limit 0,3;

// 每页显示m条数据,当前显示第n页,求第n页的数据
select * from students where is_delete=0 limit (n-1)*m,m
连接查询

当查询结果的列来源于多张表时,需要将多张表连接成一个大的数据集,再选择合适的列返回。
mysql支持三种类型的连接查询,分别为:

select * from 表1 inner join 表2 on 表1.列 = 表2.列

// 查询 能够对应班级的学生及班级信息
select * from students inner join classes on students.cls_id = classes.id;
select * from students as s inner join classes as c on s.cls_id = c.id;
// 按要求显示姓名 班级
select students.*, classes.name from students inner join classes on students.cls_id = classes.id;
select students.name, classes.name from students inner join classes on students.cls_id = classes.id;
select s.name, c.name from students as s inner join classes as c on s.cls_id = c.id;
// 查询 能够对应班级的学生以及班级信息,按照班级进行排序,同一个班级按序号排序
select c.name, s.* from students as s inner join classes as c on s.cls_id = c.id order by c.name, s.id;
屏幕快照 2019-07-04 上午11.20.20.png
// 查询每位学生对应的班级信息
select * from students left join classes on students.cls_id=classes.id;
// 显示students表中所有数据,对应classes中没有值的字段显示NULL

// 查询没有对应班级的学生信息
select * from students left join classes on students.cls_id=classes.id having classes.id = null;
select * from students left join classes on students.cls_id=classes.id where classes.id = null;
// 从查出结果集中查询数据用having
// 从一个新的表中查询数据用where

注:用的比较少 将数据表名字互换位置 用left join完成

// 使用右连接查询班级表与学生表
select * from students as s right join classes as c on s.cls_id = c.id;
// 查询学生姓名及班级名称
select s.name,c.name from students as s inner join classes as c on s.cls_id = c.id;
自关联

设计省信息的表结构provinces
id
ptitle

设计市信息的表结构citys
id
ctitle
proid

citys表的proid表示城市所属的省,对应着provinces表的id值

存储的都是地区信息,而且每种信息的数据量有限,没必要增加一个新表,或者将来还要存储区、乡镇信息,都增加新表的开销太大。

定义表areas,结构如下:
id
atitle
pid

说明:因为省没有所属的省份,所以可以填写为null;
城市所属的省份pid,填写省所对应的编号id;
这就是自关联,表中的某一列,关联了这个表中的另外一列,但是它们的业务逻辑含义是不一样的,城市信息的pid引用的是省信息的id;
在这个表中,结构不变,可以添加区县、乡镇街道、村社区等信息;

// 创建areas表
create table areas(
    aid int primary key,
    atitle varchar(20),
    pid int
);
// 从sql文件中导入数据
source areas.sql;
// 查询一共有多少个省
select count(*) from areas where pid is null;

// 查询省的名称为“山东省”的所有城市
select city.* from areas as city
inner join areas as province on city.pid=province.aid
having province.atitle='山东省';
select province .atitle, city.atitle from areas as city
inner join areas as province on city.pid=province.aid
having province.atitle='山东省';
// 查询市的名称为“广州市”的所有区县
select dis.* from areas as dis
inner join areas as city on city.aid=dis.pid
having city.atitle='广州市';
子查询
总结
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
上一篇下一篇

猜你喜欢

热点阅读