文章目录
收录一些经常用到的sql
数据库相关
建数据库
sql
CREATE DATABASE [IF NOT EXISTS] <数据库名> [[DEFAULT] CHARACTER SET <字符集名>] [[DEFAULT] COLLATE <校对规则名>];
例如:
CREATE DATABASE IF NOT EXISTS test_db DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;
表相关
建表
sql
DROP TABLE IF EXISTS `test_table`;
CREATE TABLE `test_table`(
id int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL,
name varchar(50),
length decimal(5, 2),
UNIQUE INDEX length(id ASC)
) ENGINE = InnoDB DEFAULT CHARSET=utf8;
索引相关
添加索引
添加PRIMARY KEY主键索引
sql
ALTER TABLE `table_name` ADD PRIMARY KEY ( `column` )
添加UNIQUE唯一索引
sql
ALTER TABLE `table_name` ADD UNIQUE (`column` )
添加普通索引
sql
ALTER TABLE `table_name` ADD INDEX index_name ( `column` )
添加FULLTEXT全文索引
sql
ALTER TABLE `table_name` ADD FULLTEXT ( `column`)
添加多列索引
sql
ALTER TABLE `table_name` ADD INDEX index_name ( `column1`, `column2`, `column3` )
编码相关
查看数据库编码。
sql
SHOW variables LIKE '%char%';
查看表编码
sql
SHOW CREATE TABLE <表名>;
查看字段编码
sql
mysql> SHOW FULL COLUMNS FROM t_user;
+--------+-------------+-----------------+------+-----+---------+----------------+---------------------------------+-----------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+--------+-------------+-----------------+------+-----+---------+----------------+---------------------------------+-----------+
| ID | int | NULL | NO | PRI | NULL | auto_increment | select,insert,update,references | 主键 |
| NAME | varchar(64) | utf8_general_ci | YES | | NULL | | select,insert,update,references | 名字 |
| GENDER | varchar(5) | utf8_general_ci | YES | MUL | NULL | | select,insert,update,references | 性别 |
| MOBILE | varchar(11) | utf8_general_ci | YES | MUL | NULL | | select,insert,update,references | 手机号 |
+--------+-------------+-----------------+------+-----+---------+----------------+---------------------------------+-----------+
4 rows in set (0.00 sec)
修改编码格式
修改数据库编码格式
alter database <数据库名> character set utf8mb4;
例:alter database db_user character set utf8mb4;
修改表编码
alter table <表名> character set utf8mb4;
例:alter table user character set utf8mb4;
修改字段编码
sql
ALTER TABLE <表名> MODIFY COLUMN <字段名> <字段类型> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
例:ALTER TABLE comment MODIFY COLUMN content VARCHAR(512) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
系统变量相关
查询数据目录:SHOW VARIABLES LIKE 'datadir';