Mysql高手系列 - 第4天:DDL常见操作汇总
这是Mysql系列第4篇。
环境:mysql5.7.25,cmd命令中进行演示。
DDL:Data Define Language数据定义语言,主要用来对数据库、表进行一些管理操作。
如:建库、删库、建表、修改表、删除表、对列的增删改等等。
文中涉及到的语法用[]包含的内容属于可选项,下面做详细说明。
库的管理
创建库
create database [if not exists] 库名;
删除库
drop databases [if exists] 库名;
建库通用的写法
drop database if exists 旧库名;
create database 新库名;
示例
mysql> show databases like 'javacode2018';
+-------------------------+
| Database (javacode2018) |
+-------------------------+
| javacode2018            |
+-------------------------+
1 row in set (0.00 sec)
mysql> drop database if exists javacode2018;
Query OK, 0 rows affected (0.00 sec)
mysql> show databases like 'javacode2018';
Empty set (0.00 sec)
mysql> create database javacode2018;
Query OK, 1 row affected (0.00 sec)
show databases like 'javacode2018';列出javacode2018库信息。
表管理
创建表
create table 表名(
    字段名1 类型[(宽度)] [约束条件] [comment '字段说明'],
    字段名2 类型[(宽度)] [约束条件] [comment '字段说明'],
    字段名3 类型[(宽度)] [约束条件] [comment '字段说明']
)[表的一些设置];
注意:
- 在同一张表中,字段名不能相同
 - 宽度和约束条件为可选参数,字段名和类型是必须的
 - 最后一个字段后不能加逗号
 - 类型是用来限制 字段 必须以何种数据类型来存储记录
 - 类型其实也是对字段的约束(约束字段下的记录必须为XX类型)
 - 类型后写的 约束条件 是在类型之外的 额外添加的约束
 
约束说明
not null:标识该字段不能为空
mysql> create table test1(a int not null comment '字段a');
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test1 values (null);
ERROR 1048 (23000): Column 'a' cannot be null
mysql> insert into test1 values (1);
Query OK, 1 row affected (0.00 sec)
mysql> select * from test1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
default value:为该字段设置默认值,默认值为value
mysql> drop table IF EXISTS test2;
Query OK, 0 rows affected (0.01 sec)
mysql> create table test2(
    ->   a int not null comment '字段a',
    ->   b int not null default 0 comment '字段b'
    -> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into test2(a) values (1);
Query OK, 1 row affected (0.00 sec)
mysql> select *from test2;
+---+---+
| a | b |
+---+---+
| 1 | 0 |
+---+---+
1 row in set (0.00 sec)
上面插入时未设置b的值,自动取默认值0
primary key:标识该字段为该表的主键,可以唯一的标识记录,插入重复的会报错
两种写法,如下:
方式1:跟在列后,如下:
mysql> drop table IF EXISTS test3;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> create table test3(
    ->   a int not null comment '字段a' primary key
    -> );
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test3 (a) values (1);
Query OK, 1 row affected (0.01 sec)
mysql> insert into test3 (a) values (1);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
方式2:在所有列定义之后定义,如下:
mysql> drop table IF EXISTS test4;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> create table test4(
    ->   a int not null comment '字段a',
    ->   b int not null default 0 comment '字段b',
    ->   primary key(a)
    -> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into test4(a,b) values (1,1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test4(a,b) values (1,2);
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'
插入重复的值,会报违法主键约束
方式2支持多字段作为主键,多个之间用逗号隔开,语法:primary key(字段1,字段2,字段n),示例:
mysql> drop table IF EXISTS test7;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> create table test7(
    ->    a int not null comment '字段a',
    ->    b int not null comment '字段b',
    ->   PRIMARY KEY (a,b)
    ->  );
Query OK, 0 rows affected (0.02 sec)
mysql>
mysql> insert into test7(a,b) VALUES (1,1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test7(a,b) VALUES (1,1);
ERROR 1062 (23000): Duplicate entry '1-1' for key 'PRIMARY'
foreign key:为表中的字段设置外键
语法:foreign key(当前表的列名) references 引用的外键表(外键表中字段名称)
mysql> drop table IF EXISTS test6;
Query OK, 0 rows affected (0.01 sec)
mysql> drop table IF EXISTS test5;
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> create table test5(
    ->   a int not null comment '字段a' primary key
    -> );
Query OK, 0 rows affected (0.02 sec)
mysql>
mysql> create table test6(
    ->   b int not null comment '字段b',
    ->   ts5_a int not null,
    ->   foreign key(ts5_a) references test5(a)
    -> );
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test5 (a) values (1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test6 (b,test6.ts5_a) values (1,1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test6 (b,test6.ts5_a) values (2,2);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`javacode2018`.`test6`, CONSTRAINT `test6_ibfk_1` FOREIGN KEY (`ts5_a`) REFERENCES `test5` (`a`))
说明:表示test6中ts5_a字段的值来源于表test5中的字段a。
注意几点:
- 两张表中需要建立外键关系的字段类型需要一致
 - 要设置外键的字段不能为主键
 - 被引用的字段需要为主键
 - 被插入的值在外键表必须存在,如上面向test6中插入ts5_a为2的时候报错了,原因:2的值在test5表中不存在
 
unique key(uq):标识该字段的值是唯一的
支持一个到多个字段,插入重复的值会报违反唯一约束,会插入失败。
定义有2种方式。
方式1:跟在字段后,如下:
mysql> drop table IF EXISTS test8;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> create table test8(
    ->    a int not null comment '字段a' unique key
    ->  );
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> insert into test8(a) VALUES (1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test8(a) VALUES (1);
ERROR 1062 (23000): Duplicate entry '1' for key 'a'
方式2:所有列定义之后定义,如下:
mysql> drop table IF EXISTS test9;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> create table test9(
    ->    a int not null comment '字段a',
    ->   unique key(a)
    ->  );
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> insert into test9(a) VALUES (1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test9(a) VALUES (1);
ERROR 1062 (23000): Duplicate entry '1' for key 'a'
方式2支持多字段,多个之间用逗号隔开,语法:primary key(字段1,字段2,字段n),示例:
mysql> drop table IF EXISTS test10;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> create table test10(
    ->   a int not null comment '字段a',
    ->   b int not null comment '字段b',
    ->   unique key(a,b)
    -> );
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> insert into test10(a,b) VALUES (1,1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test10(a,b) VALUES (1,1);
ERROR 1062 (23000): Duplicate entry '1-1' for key 'a'
auto_increment:标识该字段的值自动增长(整数类型,而且为主键)
mysql> drop table IF EXISTS test11;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> create table test11(
    ->   a int not null AUTO_INCREMENT PRIMARY KEY comment '字段a',
    ->   b int not null comment '字段b'
    -> );
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> insert into test11(b) VALUES (10);
Query OK, 1 row affected (0.00 sec)
mysql> insert into test11(b) VALUES (20);
Query OK, 1 row affected (0.00 sec)
mysql> select * from test11;
+---+----+
| a | b  |
+---+----+
| 1 | 10 |
| 2 | 20 |
+---+----+
2 rows in set (0.00 sec)
字段a为自动增长,默认值从1开始,每次+1
关于自动增长字段的初始值、步长可以在mysql中进行设置,比如设置初始值为1万,每次增长10
注意:
自增长列当前值存储在内存中,数据库每次重启之后,会查询当前表中自增列的最大值作为当前值,如果表数据被清空之后,数据库重启了,自增列的值将从初始值开始
我们来演示一下:
mysql> delete from test11;
Query OK, 2 rows affected (0.00 sec)
mysql> insert into test11(b) VALUES (10);
Query OK, 1 row affected (0.00 sec)
mysql> select * from test11;
+---+----+
| a | b  |
+---+----+
| 3 | 10 |
+---+----+
1 row in set (0.00 sec)
上面删除了test11数据,然后插入了一条,a的值为3,执行下面操作:
删除test11数据,重启mysql,插入数据,然后看a的值是不是被初始化了?如下:
mysql> delete from test11;
Query OK, 1 row affected (0.00 sec)
mysql> select * from test11;
Empty set (0.00 sec)
mysql> exit
Bye
C:\Windows\system32>net stop mysql
mysql 服务正在停止..
mysql 服务已成功停止。
C:\Windows\system32>net start mysql
mysql 服务正在启动 .
mysql 服务已经启动成功。
C:\Windows\system32>mysql -uroot -p
Enter password: *******
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.25-log MySQL Community Server (GPL)
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use javacode2018;
Database changed
mysql> select * from test11;
Empty set (0.01 sec)
mysql> insert into test11 (b) value (100);
Query OK, 1 row affected (0.00 sec)
mysql> select * from test11;
+---+-----+
| a | b   |
+---+-----+
| 1 | 100 |
+---+-----+
1 row in set (0.00 sec)
删除表
drop table [if exists] 表名;
修改表名
alter table 表名 rename [to] 新表名;
表设置备注
alter table 表名 comment '备注信息';
复制表
只复制表结构
create table 表名 like 被复制的表名;
如:
mysql> create table test12 like test11;
Query OK, 0 rows affected (0.01 sec)
mysql> select * from test12;
Empty set (0.00 sec)
mysql> show create table test12;
+--------+-------+
| Table  | Create Table
+--------+-------+
| test12 | CREATE TABLE `test12` (
  `a` int(11) NOT NULL AUTO_INCREMENT COMMENT '字段a',
  `b` int(11) NOT NULL COMMENT '字段b',
  PRIMARY KEY (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8     |
+--------+-------+
1 row in set (0.00 sec)
复制表结构+数据
create table 表名 [as] select 字段,... from 被复制的表 [where 条件];
如:
mysql> create table test13 as select * from test11;
Query OK, 1 row affected (0.02 sec)
Records: 1  Duplicates: 0  Warnings: 0
mysql> select * from test13;
+---+-----+
| a | b   |
+---+-----+
| 1 | 100 |
+---+-----+
1 row in set (0.00 sec)
表结构和数据都过来了。
表中列的管理
添加列
alter table 表名 add column 列名 类型 [列约束];
示例:
mysql> drop table IF EXISTS test14;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql>
mysql> create table test14(
    ->   a int not null AUTO_INCREMENT PRIMARY KEY comment '字段a'
    -> );
Query OK, 0 rows affected (0.02 sec)
mysql> alter table test14 add column b int not null default 0 comment '字段b';
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> alter table test14 add column c int not null default 0 comment '字段c';
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> insert into test14(b) values (10);
Query OK, 1 row affected (0.00 sec)
mysql> select * from test14;                                                 c
+---+----+---+
| a | b  | c |
+---+----+---+
| 1 | 10 | 0 |
+---+----+---+
1 row in set (0.00 sec)
修改列
alter table 表名 modify column 列名 新类型 [约束];
或者
alter table 表名 change column 列名 新列名 新类型 [约束];
2种方式区别:modify不能修改列名,change可以修改列名
我们看一下test14的表结构:
mysql> show create table test14;
+--------+--------+
| Table  | Create Table |
+--------+--------+
| test14 | CREATE TABLE `test14` (
  `a` int(11) NOT NULL AUTO_INCREMENT COMMENT '字段a',
  `b` int(11) NOT NULL DEFAULT '0' COMMENT '字段b',
  `c` int(11) NOT NULL DEFAULT '0' COMMENT '字段c',
  PRIMARY KEY (`a`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8       |
+--------+--------+
1 row in set (0.00 sec)
我们将字段c名字及类型修改一下,如下:
mysql> alter table test14 change column c d varchar(10) not null default '' comment '字段d';
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> show create table test14;                                                          ;;
+--------+--------+
| Table  | Create Table |
+--------+--------+
| test14 | CREATE TABLE `test14` (
  `a` int(11) NOT NULL AUTO_INCREMENT COMMENT '字段a',
  `b` int(11) NOT NULL DEFAULT '0' COMMENT '字段b',
  `d` varchar(10) NOT NULL DEFAULT '' COMMENT '字段d',
  PRIMARY KEY (`a`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8       |
+--------+--------+
1 row in set (0.00 sec)
删除列
alter table 表名 drop column 列名;
示例:
mysql> alter table test14 drop column d;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0
mysql> show create table test14;
+--------+--------+
| Table  | Create Table |
+--------+--------+
| test14 | CREATE TABLE `test14` (
  `a` int(11) NOT NULL AUTO_INCREMENT COMMENT '字段a',
  `b` int(11) NOT NULL DEFAULT '0' COMMENT '字段b',
  PRIMARY KEY (`a`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8     |
+--------+--------+
1 row in set (0.00 sec)
Mysql系列目录
对mysql感兴趣的,加一下我的微信itsoku,拉你入群交流技术。
mysql系列大概有20多篇,喜欢的请关注一下!

Mysql高手系列 - 第4天:DDL常见操作汇总的更多相关文章
- Mysql高手系列 - 第5天:DML操作汇总,确定你都会?
		
这是Mysql系列第5篇. 环境:mysql5.7.25,cmd命令中进行演示. DML(Data Manipulation Language)数据操作语言,以INSERT.UPDATE.DELETE ...
 - 四、DDL常见操作汇总
		
DDL: Data Define Language 数据定义语言,主要用来对数据库.表进行一些管理操作.如:建库.删库.建表.修改表.删除表.对列的增删改等. 一.库的管理 1.创建库 create ...
 - Mysql高手系列 - 第9篇:详解分组查询,mysql分组有大坑!
		
这是Mysql系列第9篇. 环境:mysql5.7.25,cmd命令中进行演示. 本篇内容 分组查询语法 聚合函数 单字段分组 多字段分组 分组前筛选数据 分组后筛选数据 where和having的区 ...
 - Mysql高手系列 - 第13篇:细说NULL导致的神坑,让人防不胜防
		
这是Mysql系列第13篇. 环境:mysql5.7.25,cmd命令中进行演示. 当数据的值为NULL的时候,可能出现各种意想不到的效果,让人防不胜防,我们来看看NULL导致的各种神坑,如何避免? ...
 - Mysql高手系列 - 第7篇:玩转select条件查询,避免踩坑
		
这是Mysql系列第7篇. 环境:mysql5.7.25,cmd命令中进行演示. 电商中:我们想查看某个用户所有的订单,或者想查看某个用户在某个时间段内所有的订单,此时我们需要对订单表数据进行筛选,按 ...
 - Mysql高手系列 - 第8篇:详解排序和分页(order by & limit),及存在的坑
		
这是Mysql系列第8篇. 环境:mysql5.7.25,cmd命令中进行演示. 代码中被[]包含的表示可选,|符号分开的表示可选其一. 本章内容 详解排序查询 详解limit limit存在的坑 分 ...
 - Mysql高手系列 - 第11篇:深入了解连接查询及原理
		
这是Mysql系列第11篇. 环境:mysql5.7.25,cmd命令中进行演示. 当我们查询的数据来源于多张表的时候,我们需要用到连接查询,连接查询使用率非常高,希望大家都务必掌握. 本文内容 笛卡 ...
 - Mysql高手系列 - 第10篇:常用的几十个函数详解,收藏慢慢看
		
这是Mysql系列第10篇. 环境:mysql5.7.25,cmd命令中进行演示. MySQL 数值型函数 函数名称 作 用 abs 求绝对值 sqrt 求二次方根 mod 求余数 ceil 和 ce ...
 - Mysql高手系列 - 第12篇:子查询详解
		
这是Mysql系列第12篇. 环境:mysql5.7.25,cmd命令中进行演示. 本章节非常重要. 子查询 出现在select语句中的select语句,称为子查询或内查询. 外部的select查询语 ...
 
随机推荐
- Jmeter CSV config使用
			
1.添加线程组,自己给线程组命名 2.添加CSV data set config 如上,filename是文件的名字 新增.txt文件,将变量写在文件中,完成后,更名为.csv:变量之间用逗号隔开(第 ...
 - 1.4.3 ID遍历爬虫(每天一更)
			
# -*- coding: utf-8 -*- ''' Created on 2019年5月7日 @author: 薛卫卫 ''' import itertools import urllib.req ...
 - hexo的环境变量被删除怎么办
			
这篇文章主要讲在path这一环境变量被删除的情况下,补上哪些环境变量才可以使hexo重新使用. 前两天配置opencv的时候,不小心将环境变量中"path"这一项中的内容给覆盖掉了 ...
 - Java代码计算运行时间
			
突然想准确的测试一下Java代码的执行时间,在网上找了一会.发现基本有以下两种方法:第一种是以毫秒为单位计算的. Java代码 //伪代码 long startTime=System.currentT ...
 - Unity基于NGUI的简单并可直接使用的虚拟摇杆实现(一)
			
可能大家都听说过大名鼎鼎的easytouch,然而easytouch是基于UGUI的,两种不同的UI混用,可能会造成项目管理的混乱,并且可能会出现各种幺蛾子,比如事件传递互相扰乱的问题. 于是就想找一 ...
 - 有容云:上车 | 听老司机谈Docker安全合规建设
			
编者注: 本文根据7月19日DockOne社群分享内容整理而成,分享嘉宾蒋运龙,有容云高级咨询顾问,一个IT的老兵,十年来混迹于存储.三网融合.多屏互动.智能穿戴.第三方支付.Docker等行业:经历 ...
 - 深入理解JVM-类加载器深入解析(3)
			
深入理解JVM-类加载器深入解析(3) 获得ClassLoader的途径 获得当前类的ClassLoader clazz.getClassLoader() 获得当前线程上下文的ClassLoader ...
 - Apache ActiveMQ任意文件写入漏洞(CVE-2016-3088)复现
			
Apache ActiveMQ任意文件写入漏洞(CVE-2016-3088)复现 一.漏洞描述 该漏洞出现在fileserver应用中,漏洞原理:ActiveMQ中的fileserver服务允许用户通 ...
 - ieda控制台缓冲区限制问题
			
一.现象 控制台输出数据若超过默认值时,将从后向前取默认值大小数据(1024) 二.解决方案 1.配置文件(idea安装目录/bin/idea.properties) 2.找到该栏:idea.cycl ...
 - java并发编程(十四)----(JUC原子类)对象的属性修改类型介绍
			
今天我们介绍原子类的最后一个类型--对象的属性修改类型: AtomicIntegerFieldUpdater,AtomicLongFieldUpdater,AtomicReferenceFieldUp ...