MySQL常用建表、添加字段、修改字段、添加索引SQL语句写法

2023-02-12 17:18:05 总阅读量:278,本日阅读:4,本周阅读:19,本月阅读:278 0条

建表:

DROP TABLE IF EXISTS `cms_block`;
CREATE TABLE `cms_block` (
  `id` int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键/自增',
  `title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '标签标题',
  `name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '标签标识',
  `info` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '内容',
  `uptime` int NULL DEFAULT 0 COMMENT '更新时间',
  `addtime` int NULL DEFAULT 0 COMMENT '添加时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '碎片标签' ROW_FORMAT = DYNAMIC;

修改原有字段名称及类型:

ALTER TABLE bulletin CHANGE uid username VARCHAR(50) NOT NULL DEFAULT '';

添加新字段:

alter table bulletin add citycode varchar(6) not null default 0; # 城市代码

1.创建数据库时设置编码

create database test character set utf8;

2.创建表时设置编码

create table test(id int primary key)DEFAULT charset=utf8;

3.修改数据库编码

alter database test character set utf8;

4.修改表默认编码

alter table test character set utf8;

5.修改字段编码

alter table test modify col_name varchar(50) CHARACTER SET utf8;

添加索引方法

1.添加PRIMARY KEY(主键索引)

mysql>ALTER TABLE `table_name` ADD PRIMARY KEY ( `column` )

2.添加UNIQUE(唯一索引)

mysql>ALTER TABLE `table_name` ADD UNIQUE (
`column`
)

3.添加INDEX(普通索引)

mysql>ALTER TABLE `table_name` ADD INDEX index_name ( `column` )

4.添加FULLTEXT(全文索引)

mysql>ALTER TABLE `table_name` ADD FULLTEXT (
`column`
)

5.添加多列索引

mysql>ALTER TABLE `table_name` ADD INDEX index_name ( `column1`, `column2`, `column3` )
标签 SQL MySQL

非特殊说明,本博所有文章均为博主原创。

-----