mysql.exe -h localhost -P 3306 -u root -p
use mydb; —— 进入数据库
查看:show index from 表名\G
desc:查看表结构
select * from 表名:查询所有数据
联合查询
基本语法:
select 语句1
union [union 选项]
select 语句2……
union 选项
all:保留所有,不管重复
distinct:去重,默认的
-- 联合查询
select * from my_class
union -- 默认去重
select * from my_class;
select * from my_class
union all -- 不去重
select * from my_class;
select id,c_name,room from my_class
union all -- 不去重
select name,number,id from my_student;
-- 需求:男生升序,女生降序(年龄)
(select * from my_student where sex='男' order by age asc limit 9999999)
union
(select * from my_student where sex='女' order by age desc limit 9999999);
子查询
按位置分类
from子查询
where子查询
exists子查询
按结果分类(不用背,了解,不考)
标量子查询:一行一列
列子查询:一列多行
行子查询:多列一行/多行多列
表子查询:多行多列
-- 标量子查询
select * from my_student where c_id=(select id from my_class where c_name='Python1910');-- id一定只有一个值(一行一列)
列子查询
=any等价于in; -- 其中一个即可
any等价于some; -- 二者是一样的
=all为全部
-- 列子查询(in偶尔用)
select * from my_student where c_id in(select id from my_class);
-- any,some,all——肯定(不常用,了解)
select * from my_student where c_id=any(select id from my_class);
select * from my_student where c_id=some(select id from my_class);
select * from my_student where c_id=all(select id from my_class);
-- any,some,all——否定(不常用,了解)
select * from my_student where c_id!=any(select id from my_class);-- 所有的结果(NULL除外)
select * from my_student where c_id!=some(select id from my_class);-- 所有的结果(NULL除外)
select * from my_student where c_id!=all(select id from my_class);--(NULL除外)
-- 查询年龄最大且身高最高
select * from my_student where
age=(select max(age) from my_student)
and
height=(select max(height) from my_student);
-- 行子查询
select * from my_student where
-- (age,height)称为行元素
(age,height)=(select max(age),max(height) from
my_student);
select * from my_student order by age desc,height desc limit 1;-- 可能查询结果不是预想的
-- 表子查询
select * from my_student group by c_id order by height desc;-- 不符合要求(每个班取第一个再排序)
-- 插入学生
insert into my_student values
(null,'bc20200007','小红','女',33,185,1);
-- 查找每个班身高最高的学生(加limit 9999999才能查出预想结果,有的不加也行,根据数据库版本决定)
select * from (select * from my_student order by
height desc limit 9999999) as student group by c_id;-- 每个班选出第一个学生
exists子查询
select exists(select * from my_student);
select exists(select * from my_student where id=100);
-- exists子查询
select * from my_student where
exists(select * from my_class);-- 是否成立
select * from my_student where
exists(select * from my_class where id=3);
select * from my_student where
exists(select * from my_class where id=2);