1. 程式人生 > 實用技巧 >DDL 資料定義語言

DDL 資料定義語言

目錄

建立資料庫(CREATE)

# 語法
mysql> help create database
Name: 'CREATE DATABASE'
Description:
Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification] ...

create_specification:
    [DEFAULT] CHARACTER SET [=] charset_name | [DEFAULT] COLLATE [=] collation_name
# 建立資料庫
mysql> create database mydb01;
Query OK, 1 row affected (0.00 sec)

mysql> create SCHEMA mydb02;
Query OK, 1 row affected (0.00 sec)
# 建庫時提示已存在,可以使用 IF NOT EXISTS 避免報錯
mysql> create database mydb;
ERROR 1007 (HY000): Can't create database 'mydb'; database exists

mysql> create database IF NOT EXISTS mydb;
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> create database IF NOT EXISTS mydb;
Query OK, 1 row affected, 1 warning (0.00 sec)
# 檢視建庫語句
mysql> show create database mydb;
+----------+-----------------------------------------------------------------+
| Database | Create Database                                                 |
+----------+-----------------------------------------------------------------+
| mydb     | CREATE DATABASE `mydb` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+-----------------------------------------------------------------+
1 row in set (0.00 sec)
# 建立資料庫並指定字符集
mysql> create database db3 charset utf8 COLLATE utf8_general_ci;
Query OK, 1 row affected (0.00 sec)

mysql> show create database db3;
+----------+--------------------------------------------------------------+
| Database | Create Database                                              |
+----------+--------------------------------------------------------------+
| db3      | CREATE DATABASE `db3` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+--------------------------------------------------------------+
1 row in set (0.00 sec)

# 不指定校驗規則預設就是 utf8_general_ci
mysql> create database db4 charset utf8;
Query OK, 1 row affected (0.00 sec)

刪除資料庫(DROP)

mysql> drop database db1;
Query OK, 0 rows affected (0.00 sec)

修改資料庫(ALTER)

mysql> show create database db2;
+----------+----------------------------------------------------------------+
| Database | Create Database                                                |
+----------+----------------------------------------------------------------+
| db2      | CREATE DATABASE `db2` /*!40100 DEFAULT CHARACTER SET latin1 */ |
+----------+----------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> alter database db2 charset utf8 collate utf8_general_ci;
Query OK, 1 row affected (0.00 sec)

mysql> show create database db2;
+----------+--------------------------------------------------------------+
| Database | Create Database                                              |
+----------+--------------------------------------------------------------+
| db2      | CREATE DATABASE `db2` /*!40100 DEFAULT CHARACTER SET utf8 */ |
+----------+--------------------------------------------------------------+
1 row in set (0.00 sec)

建立資料表(CREATE)

# 語法
mysql> help create table;
Name: 'CREATE TABLE'
Description:
Syntax:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    (create_definition,...)
    [table_options]
    [partition_options]

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    [(create_definition,...)]
    [table_options]
    [partition_options]
    [IGNORE | REPLACE]
    [AS] query_expression

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
    { LIKE old_tbl_name | (LIKE old_tbl_name) }
# 建表
# 1.進入一個庫
mysql> use db2
Database changed
# 2.檢視當前所在庫
mysql> select database();
+------------+
| database() |
+------------+
| db2        |
+------------+
1 row in set (0.00 sec)

# 3.1 建表,建表最少有一列
mysql> create table tb1;
ERROR 1113 (42000): A table must have at least 1 column

mysql> create table tb1(id int);
Query OK, 0 rows affected (0.04 sec)

# 3.2 建表,建表有多個列
mysql> create table student(
    -> id int,
    -> name varchar(12),
    -> age tinyint,
    -> gender enum('M','F'),
    -> cometime datetime);
Query OK, 0 rows affected (0.01 sec)

# 3.3 插入資料
mysql> insert into student values(1,'wqh',18,'male',now());
...
......
mysql> select * from student;
+------+------+------+--------+---------------------+
| id   | name | age  | gender | time                |
+------+------+------+--------+---------------------+
|    1 | wqh  |   18 | male   | 2020-07-14 20:58:52 |
|    2 | wzh  |   18 | male   | 2020-07-14 20:58:58 |
|    3 | djd  |   18 | male   | 2020-07-14 21:00:24 |
|    4 | tcy  |   18 | female | 2020-07-14 21:00:33 |
|    5 | gsp  |   18 | male   | 2020-07-14 21:00:43 |
|    6 | cjq  |   18 | male   | 2020-07-14 21:00:53 |
+------+------+------+--------+---------------------+
6 rows in set (0.00 sec)


# 4.查看錶
mysql> show tables;
+---------------+
| Tables_in_db2 |
+---------------+
| tb1           |
+---------------+
1 row in set (0.00 sec)

mysql> desc tb1;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

資料表的資料屬性

# 檢視建立資料表的語句
mysql> show create table students;
| students | CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '學生id',
  `name` varchar(12) NOT NULL COMMENT '學生姓名',
  `age` tinyint(3) unsigned NOT NULL COMMENT '學生年齡',
  `gender` enum('M','F') DEFAULT 'M' COMMENT '學生性別',
  `cometime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '入學時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8                   |
1 row in set (0.00 sec)

# 檢視資料表的詳細描述
mysql> desc students;
+----------+---------------------+------+-----+-------------------+----------------+
| Field    | Type                | Null | Key | Default           | Extra          |
+----------+---------------------+------+-----+-------------------+----------------+
| id       | int(11)             | NO   | PRI | NULL              | auto_increment |
| name     | varchar(12)         | NO   |     | NULL              |                |
| age      | tinyint(3) unsigned | NO   |     | NULL              |                |
| gender   | enum('M','F')       | YES  |     | M                 |                |
| cometime | datetime            | YES  |     | CURRENT_TIMESTAMP |                |
+----------+---------------------+------+-----+-------------------+----------------+
5 rows in set (0.00 sec)

資料型別屬性(Type)

# 欄位資料型別(Type)

int				整數,範圍 -2^31 - 2^31-1   # 即 -2147483648 - 2147483647
tinyint			最小整數   -128 - 127		# 如年齡,如果設定欄位值非負數,範圍變化為 0 - 255
varchar			字元型別(變長)	# 如身份證號
char			字元型別(定長)	# 如名字
enum			列舉型別		# 如性別,給其固定選項,只能選則固定選項中的值
datetime		時間型別		# 年月日時分秒
date			時間型別		# 年月日

# int 型別
mysql> create table tb1(id int);
Query OK, 0 rows affected (0.04 sec)

mysql> insert tb1 values(1);
Query OK, 1 row affected (0.01 sec)

# 下面這條雖然報錯,但其實會顯示 11111111111 ,因為 my.cnf 的一條預設配置(最底行)
mysql> insert tb1 values(11111111111);
ERROR 1264 (22003): Out of range value for column 'id' at row 1

# 刪除預設配置,找到 /etc/my.cnf 刪除下面的行
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

# 刪除預設配置後,不論插入多大的值,最大隻能是 2147483647,最小隻能是 -2147483648
mysql> insert tb1 values(2147483647);
Query OK, 1 row affected (0.00 sec)
# 報錯,但插入成功,資料表中顯示資料為 2147483647
mysql> insert tb1 values(2147483648);
ERROR 1264 (22003): Out of range value for column 'id' at row 1

mysql> insert tb1 values(-2147483648);
Query OK, 1 row affected (0.00 sec)
# 報錯,但插入成功,資料表中顯示資料為 -2147483648
mysql> insert tb1 values(-2147483649);
ERROR 1264 (22003): Out of range value for column 'id' at row 1

# enum 型別
mysql> create table tb2(id int,sex enum('male','female'));
Query OK, 0 rows affected (0.02 sec)

mysql> insert into tb2 values(1,'male');
Query OK, 1 row affected (0.00 sec)
# 如果插入的資料不符合 enum 型別設定的固定選項,會報錯、或者值為空
mysql> insert into tb2 values(1,'other');
ERROR 1265 (01000): Data truncated for column 'sex' at row 1

其他屬性(Null,Key,Default,Extra)

NOT NULL: 			# 非空
PRIMARY KEY: 		# 主鍵(唯一且非空的)
AUTO_INCREMENT: 	# 自增(此列必須是:PRIMARY KEY 或者 UNIQUE KEY)
UNIQUE KEY: 		# 唯一鍵,單獨的唯一的
DEAFULT: 			# 預設值
UNSIGNED: 			# 非負數
COMMENT: 			# 註釋

建立資料表(設定更多屬性)

# 1.建表語句
create table students(
id int primary key auto_increment comment "學生id",
name varchar(12) not null comment "學生姓名",
age tinyint unsigned not null comment "學生年齡",
gender enum('M','F') default 'M' comment "學生性別",
cometime datetime default now() comment "入學時間");

# 2.檢視建表語句
mysql> show create table students;
| students | CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '學生id',
  `name` varchar(12) NOT NULL COMMENT '學生姓名',
  `age` tinyint(3) unsigned NOT NULL COMMENT '學生年齡',
  `gender` enum('M','F') DEFAULT 'M' COMMENT '學生性別',
  `cometime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '入學時間',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8                   |
1 row in set (0.00 sec)

# 3.插入資料
mysql> insert into students values(1,'zzzwqh',18,'M',now());
Query OK, 1 row affected (0.00 sec)
# 因為主鍵相同無法插入資料
mysql> insert into students values(1,'zzzwqh',18,'M',now());
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
# 正確插入資料方法
mysql> insert into students values('2','zzzwqh',18,'M',now());
Query OK, 1 row affected (0.00 sec)
# 主鍵已經設定自增沒必要自己插入

# 插入資料的正規書寫格式
mysql> insert students(name,age) values('wqh',18);
Query OK, 1 row affected (0.00 sec)

mysql> insert students(name,age,gender) values('laowang',12,'M');
Query OK, 1 row affected (0.01 sec)

mysql> select * from students;
+----+--------+-----+--------+---------------------+
| id | name   | age | gender | cometime            |
+----+--------+-----+--------+---------------------+
|  1 | zzzwqh |  18 | M      | 2020-07-14 19:51:44 |
|  2 | zzzwqh |  18 | M      | 2020-07-14 19:52:19 |
|  3 | wqh    |  18 | M      | 2020-07-14 19:53:50 |
|  4 | laowang|  12 | M      | 2020-07-14 19:53:58 |
+----+--------+-----+--------+---------------------+
4 rows in set (0.00 sec)

刪除資料表(DROP)

# 刪除資料表 student
mysql> drop table student;

修改資料表(ALTER)

# 1.新建表
mysql> create table tabletest(daijiadong tinyint);
Query OK, 0 rows affected (0.04 sec

# 2.修改表名
mysql> alter table tabletest rename stu;
Query OK, 0 rows affected (0.01 sec)

# 3.插入新欄位
mysql> alter table stu add rengyufeng int;
Query OK, 0 rows affected (0.14 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+------------+------------+------+-----+---------+-------+
| Field      | Type       | Null | Key | Default | Extra |
+------------+------------+------+-----+---------+-------+
| daijiadong | tinyint(4) | YES  |     | NULL    |       |
| rengyufeng | int(11)    | YES  |     | NULL    |       |
+------------+------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

# 4.插入多個新欄位
mysql> alter table stu add liukong int,add wangzhangxing int;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+---------------+------------+------+-----+---------+-------+
| Field         | Type       | Null | Key | Default | Extra |
+---------------+------------+------+-----+---------+-------+
| daijiadong    | tinyint(4) | YES  |     | NULL    |       |
| rengyufeng    | int(11)    | YES  |     | NULL    |       |
| liukong       | int(11)    | YES  |     | NULL    |       |
| wangzhangxing | int(11)    | YES  |     | NULL    |       |
+---------------+------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

# 5.插入欄位到最前面
mysql> alter table stu add kangpeiwen varchar(100) first;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| kangpeiwen    | varchar(100) | YES  |     | NULL    |       |
| daijiadong    | tinyint(4)   | YES  |     | NULL    |       |
| rengyufeng    | int(11)      | YES  |     | NULL    |       |
| liukong       | int(11)      | YES  |     | NULL    |       |
| wangzhangxing | int(11)      | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+
5 rows in set (0.01 sec)

# 6.插入欄位到指定欄位後面
mysql> alter table stu add chenjianqing varchar(100) after daijiadong;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| kangpeiwen    | varchar(100) | YES  |     | NULL    |       |
| daijiadong    | tinyint(4)   | YES  |     | NULL    |       |
| chenjianqing  | varchar(100) | YES  |     | NULL    |       |
| rengyufeng    | int(11)      | YES  |     | NULL    |       |
| liukong       | int(11)      | YES  |     | NULL    |       |
| wangzhangxing | int(11)      | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

# 7.刪除指定列
mysql> alter table stu drop daijiadong;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| kangpeiwen    | varchar(100) | YES  |     | NULL    |       |
| chenjianqing  | varchar(100) | YES  |     | NULL    |       |
| rengyufeng    | int(11)      | YES  |     | NULL    |       |
| liukong       | int(11)      | YES  |     | NULL    |       |
| wangzhangxing | int(11)      | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

# 8.修改欄位
mysql> alter table stu change rengyufeng congtianqi int;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| kangpeiwen    | varchar(100) | YES  |     | NULL    |       |
| chenjianqing  | varchar(100) | YES  |     | NULL    |       |
| congtianqi    | int(11)      | YES  |     | NULL    |       |
| liukong       | int(11)      | YES  |     | NULL    |       |
| wangzhangxing | int(11)      | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

# 9.修改欄位屬性
mysql> alter table stu modify congtianqi tinyint;
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc stu;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| kangpeiwen    | varchar(100) | YES  |     | NULL    |       |
| chenjianqing  | varchar(100) | YES  |     | NULL    |       |
| congtianqi    | tinyint(4)   | YES  |     | NULL    |       |
| liukong       | int(11)      | YES  |     | NULL    |       |
| wangzhangxing | int(11)      | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+
5 rows in set (0.01 sec)