一、基本概念
1、MySQL中“键”和“索引”的定义相同,所以外键和主键一样也是索引的一种。不同的是MySQL会自动为所有表的主键进行索引,但是外键字段必须由用户进行明确的索引。用于外键关系的字段必须在所有的参照表中进行明确地索引,InnoDB不能自动地创建索引。
2、外键可以是一对一的,一个表的记录只能与另一个表的一条记录连接,或者是一对多的,一个表的记录与另一个表的多条记录连接。
3、如果需要更好的性能,并且不需要完整性检查,可以选择使用MyISAM表类型,如果想要在MySQL中根据参照完整性来建立表并且希望在此基础上保持良好的性能,最好选择表结构为innoDB类型。
4、外键的使用条件
① 两个表必须是InnoDB表,MyISAM表暂时不支持外键
② 外键列必须建立了索引,MySQL 4.1.2以后的版本在建立外键时会自动创建索引,但如果在较早的版本则需要显式建立;
③ 外键关系的两个表的列必须是数据类型相似,也就是可以相互转换类型的列,比如int和tinyint可以,而int和char则不可以;
5、外键的好处:可以使得两张表关联,保证数据的一致性和实现一些级联操作。保持数据一致性,完整性,主要目的是控制存储在外键表中的数据。 使两张表形成关联,外键只能引用外表中的列的值!可以使得两张表关联,保证数据的一致性和实现一些级联操作;
数据库连接
mysql -u root -p123456
查看表
show databases
创建数据库设置编码
create table books character set utf8;
创建用户
-- 特别需要注意,在 MySQL 中,账号由两部分组成:
-- 1. user
-- 2. host
-- 即使 user 相同,只要 host 不同,也会被认为是不同账号。
-- 这样可以非常方便对来自不同 ip 地址的访问进行精细的权限控制。
-- 默认情况下,创建的用户 host 为 '%',这是一个匹配符,跟模糊查询里的意思一样,表示匹配所有
create user [用户名] identified by '[密码]';
create user vip identified by 'vippp'; -- 所有连接
create user vip@'127.0.0.1' identified by 'xxx'; -- 本地连接
create user vip@'192.168.%' identified by 'yyy'; -- 192.168 网段的连接
修改密码
set passwor from ‘用户名’ @host=password(‘新密码’);
update mysql.user set password=password(‘新密码’) where user=’用户名’ and host=’%’;
删除用户
drop user 用户名;
delete from mysql.user where user=’用户名’ and host=’%’
给权限
grant all on *.* to vip@’127.0.0.1′; –将所有数据库上的所有权利都授予通过本机连接的VIP用户;
grant all privileges on books.* to vip@’%’; –将数据库books上的说有权利都授予所有连接的vip用户;
grant select on books.users to vip@’%’; –将books数据库上的users表的访问权限开发给vip用户;
grant all on *.* to vip@’%’ with grant potions; –witgrant potionss的意思是可以给vip给予权限给别的用户
查看权限
show grants for vip@’%’;
进行冲刷
flush privileges
查看当前用户
select user() ,current_user();
创建表
create table 表名
判断存在就删除然后创建
creata table if exists 表名
drop table if exists 表名
创建临时表
create temporary table 表名
mysql自增长
auto_increment
添加外键约束
alter table 表名 add constraint fk_引用id foreign key(引用id) references 被引用表名 (被引用id)
添加主键约束
alter table 表名 add constraint pk_id primary key (id);
删除约束
alter table 表名 drop forign key fk_引用id
添加表的字段
alter table 表名 add 字段名 类型 ;
修改表中的字段为空
alter table 表名 modify 字段名 类型 null
修改表中的字段不为空
alter table 表名 modify 字段名 类型 not null
添加表的字段自增主键
alter table 表名 add column 字段名 类型 auto_increment not null, add primary key(cid);
删除表的字段
alter table 表名 drop column 字段;
删除表的主键
alter table 表名 drop primary key;
创建存储过程 mysql存储100相加的和
create procedure sum(a int)
begin
set @i=0;
set @j=0;
repeat
set @i=@i+1;
set @j=@i+@j;
until a=@i end
repeat;
end $
–能整除三 不能整除9
delimiter $
create procedure asdw(sss int)
begin
set @i=0;
set @cj=1;
repeat
set @i=@i+1;
if @i%3=0 && @i%9!=0 then
set @cj=@cj*@i;
end if;
until @i=sss end repeat;
end
创建索引
CREATE INDEX 索引名字 ON 表名(字段名)