mysql 语句 注意行尾' ; '结束
创建用户
mysql> CREATE USER ‘lucy'@'%' IDENTIFIED BY 'huahua';
给用户赋予权限
mysql> GRANT ALL ON . TO ‘lucy'@'%';
使更改立即生效
mysql> FLUSH PRIVILEGES;
退出
mysql> \q
Mysql –ulucy –phuahua; #进入新用户
查看当前用户:
SELECT USER( );
查看当前数据库:
Select database();
创建数据库 语法:
CREATE DATABASE [IF NOT EXISTS] db_name;
重复创建会报错,所以可以加上if not exists
查看有哪些数据库:
SHOW DATABASES;
删除数据库 语法:
DROP DATABASE [IF EXISTS] dbname;
如果不知道数据库,是否存在,
记得加if exists #加了if exists 不管存不存在都不会报错
和数据有关的 删除 用del
无关的用drop ,drop table drop database
进入 数据库 语法:
USE DBNAME; # use 数据库名
创建表 语法:
CREATE TABLE [IF NOT EXISTS] table_name( #创建表 如果不存在表名
column_name data_type, # 列名 数据类型,(多字段用, 隔开)
)
数据类型:
INT 整数类型
VARCHAR 字符串
创建表 test test有二个字段 id (int 类型), name(字符串类型最大长度20)
mysql>create table if not exists test(
-> id int
-> name varchar(20)
-> );
查看有哪些表:
SHOW tables;
查看数据表结构 语法:
DESCRIBE tb_name; #查看表结构
SHOW CREATE TABLE tb_name;(\G)
表约束
手动,添加非空约束
(必须这个字段,没有NULL值)
mysql> alter table tb1
-> modify id int not null;
取消非空约束
mysql> alter table tb1
-> modify id int ;
添加唯一约束
mysql> alter table tb2
-> add unique key(name)
->;
删除唯一约束
mysql> alter table tb2
-> drop key name; #drop 字段名 直接删除字段
主键约束 primary key
主键的作用: 可以唯一标识 一条数据,每张表里面只能有一个主键,。主键的主要目的是帮助MySQL以最快的速度查找到表中的某一条信息
主键特性: 非空且唯一。当表里没有主键的时,第一个出现的非空且为唯一的列,被当成主键。
删除主键约束
mysql -> alter table tb3
-> drop primary key;
添加主键约束
mysql> alter table tb3
-> add primary key(id);
自增长 auto_increment
auto_increment :自动编号,一般与主键组合使用。一个表里面只有一个自增默认情况下,起始值为1,每次的增量为1。
例子:
create table tb1(
id int primary key auto_increment,
name varchar(20)
)auto_increment =100;自动增长初始值100
删除自动增长
mysql> alter table tb5
-> modify id int;
增加自动增长auto_increment
mysql> alter table tb5
-> modify id int auto_increment;
默认约束 default
default :初始值设置,插入记录时,如果没有明确为字段赋值,则自动赋予默认值。
例子:
create table tb6(
id int primary key auto_increment,
name varchar(20) not null,
age int not null default 18
);
删除default
mysql> alter table tb6
-> modify age int;
mysql> alter table tb6
-> modify age int default 20;
外键约束 foreign key
外键约束 :保持数据一致性,完整性实现一对多关系。
外键必须关联到键上面去,一般情况是,关联到另一张表的主键
(因为一个表只存一类信息。用外键来做参照,保证数据的一致性,可以减少数据冗余)
表a
create table a(
a_id int primary key auto_increment,
a_name varchar(20) not null
);
insert into a values(1,'a1'),(2,'a2');
表b
create table b(
b_id int primary key,
b_name varchar(20) not null,
fy_id int not null,
constraint AB_id foreign key(fy_id) references a(a_id)
);
删除外键
alter table b drop foreign key AB_id;
增加外键
mysql> alter table b
-> add constraint AB_id foreign key(fy_id) references a(a_id);
B表中的fy_id 字段,只能添加 a_id中 已有的数据。
A表中a_id 被参照的数据, 不能被修改和删除
考驾照
学员表(身份证号,姓名,性别) # 主键 身份证号 特性:非空且唯一�科目表(科目号,科目内容,扣分) # 主键 科目号 �成绩表(身份证号,科目号,成绩) # 联合主键 身份证号 + 科目号 � �成绩表中的身份证号是学员表的外键 ,成绩表中的科目号是科目表的外键 � �主键和外键是为了维护关系数据库的完整性:�1.主键是能确定一条记录的唯一标识 �2.外键用于与其他表建立联系。是能确定另一张表记录的字段,用于保持数据的一致性。
网友评论