MySQL常用语句不完全总结

建库

create database 数据库名;

删库

drop database 数据库名;

更安全的方式
drop database if exists 数据库名;

建表

create table 表名(
字段1 字段名,
字段2 字段名,
···
字段n 字段名
);

删表

drop table 表名;

插入一条记录

insert into 表名 (字段1,字段2,字段3,…字段n) values(值1,值2,值3,…值n);

还可以省略字段,直接赋值(注意一定要按对应的字段赋值)
insert into 表名 values(值1,值2,值3,…值n);

修改一条记录

update 表名 set 列名1=值1 where 某字段 = 条件;
exp: update student_table set name = ‘张三’ where id = 1;

删除一条记录

delete from 表名 where 某字段 = 条件;

查询一条记录

select 字段1,字段2,字段3,…字段n from 表名 ;
可以用 * 代表所有字段
select * from 表名;

alter table 表名 modify 字段 字段类型 ;
alter table 表名 change 字段名 新的字段名 字段类型;

添加列

alter table 表名 add 列名 字段类型;

删除列

alter table 表名 drop column 列名;

修改列

其一:修改列的类型
alter table 表名 modify 列名 字段类型;
其二:修改列的名称和类型
alter table 表名 change 原列名 新列名 字段类型;

创建表后添加主键约束

alter table 表名 add primary key(字段);

修改主键约束

alter table 表名 modify 某字段 字段类型 primary key;

创建表后删除主键约束

alter table 表名 drop primary key;

删除唯一约束

alter table 表名 drop index 某字段;

添加非空约束

建表时添加:
create table user(u_id int not null);
建表后添加:
alter table 表名 modify 字段 字段类型 not null;

删除非空约束

alter table 表名 modify 字段 字段类型;

添加默认约束

建表时添加:
create table user(age int default 默认值);
建表后添加:
alter table 表名 modify 字段 字段类型 default 默认值;

删除默认约束

alter table 表名 modify 字段 字段类型;

创建外键约束(涉及两个表,父表,子表)

子表
create table students(
s_id int primary key,
name varchar(20),
c_id int,
constraint fk_stu_class foreign key(c_id) references classes(c_id)
);
(constraint 作用是给你的外键约束起了名称,如果没有则会自动生成一个名称)

父表
create table classes(
c_id int primary key,
name varchar(20)
);

删除外键约束

alter table 表名 drop foreign key 外键约束名称;

注意

1.先创建主表,再创建子表
2.删除表时,必须先删除有外键约束的表,再删除对应的主表
3.子表添加外键数据时必须添加在主表已有的数据

你可能感兴趣的:(笔记,mysql)