MYSQl命令总结:1.数据类型、数据库、表、约束

数据库命令

查看数据库

show databases;

查看数据库编码

select schema_name,default_character_set_name from information_schema.schemata where schema_name = 'moonwood_wtl';

创建数据库

create database test default character set utf8;

删除数据库

drop database test;

选择数据库

use test;

表命令

查看已创建的表:

show tables;

查询表中的约束信息:

SHOW KEYS FROM 表名;

创建表:

create table employees(employee_id int,employee_name varchar(10),salary float(8,2));

创建表时添加约束:【创建 depts 表包含 department_id 该列为主键且自动增长,department_name 列不 允许重复,location_id 列不允含有空值】

create table depts(department_id int primary key auto_increment,department_name varchar(30) unique,location_id int not null);

创建表时指定列的默认值:【创建 emp3 表,该表包含 emp_id 主键且自动增长,包含 name ,包含 address 该列默认 值为”未知”】

create table emp3(emp_id int primary key auto_increment,name varchar(10),address varchar(50) default 'Unknown');

添加新列:【在 emp 表中添加佣金列,列名为 commission_pct】

alter table emp add column commission_pct float(4,2);

修改表名:【将emp表名employees修改为emp】

alter table employees rename emp;

修改表添加新列并指定默认值:【修改 emp3 表,添加job_id 该列默认值为 0】

alter table emp3 add column job_id int default 0;

修改列名:【将emp表中的employee_name修改为name】

alter table emp change column employee_name name varchar(20);

修改列类型:【将 emp 表中的 name 的长度指定为 40】

alter table emp modify name varchar(40);

删除指定列:

alter table emp drop column commission_pct;

删除表:

drop table employees;

约束

主键约束

作为主键的列相同就会报错,主键可以一个,可以多个

1.添加主键

alter table emp add primary key(employee_id);

2.修改主键为自增:

alter table emp modify employee_id int auto_increment;

3.删除主键【先去自增再删除】:

alter table emp modify employee_id int;
alter table emp drop primary key;

外键约束

Navicat设置:外键/添加外键-删除外键

1.添加外键约束【一般将别表的主键作为自己外键】:

【创建departments表】

create table departments(department_id int,department_name varchar(30),location_id int);

【向department_id列添加主键】

alter table departments add primary key(department_id);

【向department_id列主键添加自动递增】

alter table departments modify department_id int auto_increment;

【修改emp表,添加dept_id列】

alter table emp add column dept_id int;

【向emp表中的dept_id列添加外键约束】

alter table emp add constraint emp_fk foreign key(dept_id) references departments(department_id);

2.删除外键约束:

alter table emp drop foreign key emp_fk;

唯一性约束

Navicat设置:索引/创建索引名【随意】-索引的栏位-索引类型选择Unique

1.添加唯一性约束:【向emp表中的name添加唯一约束】

alter table emp add constraint emp_uk unique(name);

2.删除唯一性约束:【删除 name 的唯一约束】

alter table emp drop key emp_uk;

非空约束

Navicat设置:栏位/是否允许空值

1.添加非空约束:【向emp表中的salary添加非空约束】

alter table emp modify salary float(8,2) not NULL;

2.删除非空约束:【删除emp表中salary 的非空约束】

alter table emp modify salary float(8,2) NULL;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月木@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值