1.准备测试数据
2.as和distinct
3.where 条件查询
4. 排序
5. 分页查询
6. 聚合函数
7. 分组查询
8. 连接查询–内连接
9. 连接查询–左连接
10.连接查询–右连接
11.子查询
1.准备测试数据
-- 创建数据库
create database python_test_15;
-- 使用数据库
use python_test_15;
-- students表 1-1 1-多 多-多
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 tinyint 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期");
库里面就有两个表:
同学(students)↓↓
班级(classes)↓↓
测试数据都准备好了。
2.as和distinct关键字
-- 使用 as 给字段起别名:
select name as '姓名', age as '年龄' from students;
-- 使用 as 给表起别名:
select s.name, s.age from students as s;
-- 查询练习
-- 查询所有字段
-- select * from 表名;
select * from students;
select * from classes;
-- select 表名.字段 .... from 表名;
-- 可以通过 as 给表起别名
-- select 表别名.字段 .... from 表名 as 表别名;
select s.name as '姓名', s.age as '年龄' from students as s;
-- 消除重复行(查性别)
-- distinct 字段
-- 查询students中的所有性别
-- select gender from students; --会有很多重复数据
-- 去掉重复数据
select distinct gender from students;