常用基本SQL

1、DDL

1.1 创建表——create

create table t_article(
       id int(11) primary key auto_increment,
       name varchar(255) not null
)engine=innodb default charset=utf8;

 

1.2 修改表——alter

修改表名

两种方法:一种方法直接用 rename 关键字,另一种方法用 alter 修改表

rename table tt_user to t_user;
alter table t_user rename to tt_user;

修改列名 

alter table t_article change column name title varchar(255) not null;

修改列类型

alter table t_article modify column title varchar(255) not null;
--
alter table t_article change column title title varchar(255) not null;
--change修改时指定列名一致也可以修改列类型

修改/添加列注释

ALTER TABLE `t_user` MODIFY COLUMN `nickname`  varchar(255)  DEFAULT NULL COMMENT '用户名称' AFTER `email`;
-- AFTER `email` 表示设置列的位置,是可选的,与修改列的sql语法一样

添加列

alter table mytable add colname varchar(20);

-- 添加列并指定位置,after `sex`表示放在`sex`列的后面,
-- 可以用 first 指定为第一列
alter table `t_user` add `user_type` varchar(2) default '00' comment '用户类型' after `sex`;

 

删除列

alter table mytable drop column colname;

 

1.3 删除表——drop

drop table if exists t_article;

 

2、约束

2.1 删除外键

alter table t_user drop foreign key `fk_name`;

 2.2 添加外键

alter table `table_name` add constraint `fk_name` foreign key(`column_name`) references `other_table_name`(`column_name`);

 2.3 添加主键(复合主键)

alter table table_name add primary key (`col1`, `col2`);

 

3、索引

3.1 删除索引

drop index index_name on table_name;
alter table table_name drop index index_name;

 

posted @ 2020-12-13 13:00  liuyiyuan  阅读(96)  评论(0编辑  收藏  举报