呆鸟的Python数据分析数据库知识点

学会MySQL查询,看完这几招就会了

2018-12-23  本文已影响1人  b062c0d32d52

创建数据库、数据表

-- 创建数据库
create database test_1 charset=utf8;

-- 使用数据库
use test_1;

-- 创建students表
create table students(
id int unsigned not null primary key auto_increment,
name varchar(30) 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
);

一、查询

二、条件查询

使用 where 子句对表中的数据筛选,结果为 true 的会出现在结果集中

例:
-- 查询编号大于3的女同学
select * from students where id > 3 and gender = 2;
-- 查询编号小于8或没被删除的学生
select * from students where id < 8 or is_delete = 0;
-- 查询姓黄并且’名‘是一个字的学生
select * from students where name like '黄_';
-- 查询姓黄或叫靖的学生
select * from students where name like '黄%' or name like '%靖';
-- 查询编号是1或3或8的学生
select * from students where id in (1, 3, 8);
-- 查询编号为3至8的男生
select * from students where (id between 3 and 8) and gender=1;
-- 查询没有填写身高的学生
select * from students where height is null;

三、数据排序

为了方便查看数据,可以对数据进行排序
语法:
select * from 表名 order by 列1 asc|desc [, 列2 asc|desc,...];
说明:

四、聚合函数

为了快速得到统计数据,经常会用到如下5个聚合函数

五、分组

五、获取部分行

当数据量过大时,在一页中查看数据是一件非常麻烦的事情
语法:
select * from 表名 limit start, count;
说明:
从 start 开始,获取 count 条数据
例:查询前3行男生信息
select * from students where gender=1 limit 0,3;

六、连接查询

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

语法:
select * from 表1 inner | left | right join 表2 on 表1.列 = 表2.列;
例:
-- 使用内连接查询班级表与学生表
select * from students inner join classes on students.cls_id = classes.id;
-- 使用左连接查询班级表与学生表
select * from students as s left 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;

七、子查询

总结

上一篇 下一篇

猜你喜欢

热点阅读