MySQL第二篇
distinct :不显示字段的重复值
1、sanguo表中有哪些国家
select distinct country from sanguo;
2、sanguo表中有几个国家
select count(distinct country) from sanguo;
嵌套查询(子查询)
1、定义 :把内层的查询结果作为外层查询的条件
2、语法
select … from 表名 where 字段名 运算符 (select … from 表名 where 字段名)
1、把攻击值小于平均攻击值的英雄名字和攻击值查出来
select name,gongji from sanguo where gongji < (select avg(gongji) from sanguo);
2、找出每个国家攻击力最高的英雄的名字和攻击值
select name,gongji from sanguo where (country,gongji) in (select country,max(gongji) from sanguo group by country);
多表查询
1、笛卡尔积 :不加where条件
select ... from 表1,表2;
2、加where条件
select ... from 表1,表2 where 条件;
e.g.
select sheng.s_name,city.c_name from sheng,city where sheng.s_id=city.cfather_id;
select sheng.s_name,city.c_name,xian.x_name from sheng,city,xian where
sheng.s_id=city.cfather_id
and city.c_id=xian.xfather_id;
连接查询
1、内连接(inner join)
1、语法格式
select ... from 表1 inner join 表2 on 条件 inner join 表3 on 条件;
1、查找省、市详细信息
select sheng.s_name,city.c_name from
sheng inner join city
on sheng.s_id=city.cfather_id;
2、查找省、市、县详细信息
select sheng.s_name,city.c_name,xian.x_name from
sheng inner join city
on sheng.s_id=city.cfather_id
inner join xian
on city.c_id=xian.XFATHER_ID;
2、外连接
1、左连接(left join) 以左表为主显示查询结果
2、右连接(right join) 以右表为主显示查询结果
select sheng.s_name,city.c_name,xian.x_name from
sheng left join city
on sheng.s_id=city.cfather_id
right join xian
on city.c_id=xian.xfather_id;
约束:
1.非空约束 not null
2.默认约束
e.g. 创建表格时,设置约束
sex enum("M","F","S") not null default "S";
索引:
1、定义
对数据库表的一列或者多列的值进行排序的一种结构(BTree方式)
2、优点
加快数据的检索速度
3、缺点
1、占用物理存储空间
2、当对表中数据更新时,索引需要动态维护,占用系统资源,降低数据维护速度
4、索引分类:
1、普通索引(index) :无约束, key标志为MUL
2、唯一索引(unique):字段值不允许重复,不能Null, key标志为UNI
1、创建表创建
create table 表名(
... ...
index(name),
index(age),
unique(phnumber),
unique(cardnumber)
);
2、已有表创建
create [unique] index 索引名 on 表名(字段名);
3、查看索引
1、desc 表名; --> key标志
2、show index from 表名\G;
4、删除索引
drop index 索引名 on 表名;
主键&&外键
3、主键
1、只能有1个字段
2、约束 :字段值不允许重复,且不能为 NULL
3、KEY标志 :PRI
4、通常设置编号id为主键,能唯一锁定1条记录
4、创建表时创建
create table 表名(
id int primary key auto_increment,
...
);
5、已有表创建
alter table 表名 add primary key(id);
6、删除
1、先删除自增长
alter table 表名 modify id int;
2、删除主键
alter table 表名 drop primary key; 主键不需要主键名
7外键
1、定义
让当前表字段的值在另一个表的范围内选择
2、使用规则
1、主表、从表字段数据类型要一致
2、主表被参考字段 :主键
3、语法
创建表时添加:
foreign key(外键字段) references 主表(主键字段)
on delete 级联动作
on update 级联动作
4、删除
1、查看外键名
show create table 表名;
2、删除外键
alter table 表名 drop foreign key 外键名;
5、在已有表中添加外键(两种方法)
1.方法:
alter table 从表 add foreign key(外键字段) references 主表(主键字段)
on update cascade
on delete cascade;
2.方法:
alter table 从表 add constraint 外键名 foreign key(外键字段) references 主表(主键字段)
on update cascade
on delete cascade;
6、级联动作
1、cascade
数据级联删除、更新(参考字段)
2、set null
从表有相关联记录,字段值设置为NULL
3、restrict(默认)
从表有相关联记录,不让主表删除、更新
e.g.
create table bjtab(
stu_id int,
name varchar(15),
money smallint,
foreign key(stu_id) references banji(id)
on delete cascade
on update cascade
);