一、导入测试数据

[root@server ~]# wget https://launchpadlibrarian.net/24493586/employees_db-full-1.0.6.tar.bz2

mysql> source /root/employees_db/employees.sql ;

查看:

mysql> use employees;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+---------------------+
| Tables_in_employees |
+---------------------+
| departments |
| dept_emp |
| dept_manager |
| employees |
| salaries |
| titles |
+---------------------+
6 rows in set (0.00 sec)

二、数据表

表是关系型数据库的核心,表是记录的集合(集合中的数据是无序的)

二维表模型易于人类理解,mysql默认存储引擎都是基于行存储

每行记录都是基于列进行组织的

语法:

官网:https://dev.mysql.com/doc/refman/5.7/en/create-table.html

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name

(create_definition,...)

[table_options]

[partition_options]

create_definition:

  col_name column_definition

column_definition:
 data_type [NOT NULL | NULL] [DEFAULT default_value]
  [AUTO_INCREMENT] [UNIQUE [KEY]] [[PRIMARY] KEY]
  [COMMENT 'string']
  [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
  [STORAGE {DISK|MEMORY|DEFAULT}]
  [reference_definition]
 | data_type [GENERATED ALWAYS] AS (expression)
  [VIRTUAL | STORED] [NOT NULL | NULL]
  [UNIQUE [KEY]] [[PRIMARY] KEY]
  [COMMENT 'string']

知识点1:创建临时表(temporary)

To create a temporary table, you must have the CREATE TEMPORARY TABLES privilege

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

mysql> insert into a select 5;
Query OK, 1 row affected (0.02 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> create temporary table a ( id int);
Query OK, 0 rows affected (0.00 sec)

mysql> show tables;
+------------------+
| Tables_in_testDB |
+------------------+
| a |
+------------------+
1 row in set (0.00 sec)

mysql> select * from a;
Empty set (0.00 sec)

mysql> insert into a select 6;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> select * from a;
+------+
| id |
+------+
| 6 |
+------+
1 row in set (0.00 sec)

(综上,临时表的表明可以和实际存在的表名同名,但是建议不这样操作)

mysql> system ls /tmp -lh

-rw-r-----. 1 mysql mysql 8.4K Nov 28 16:38 #sql5ad7_f_0.frm
-rw-r-----. 1 mysql mysql 8.4K Nov 28 16:58 #sql5ad7_f_1.frm

数据存放到ibtmp1临时表空间

[root@server mysql_data1]# ll ibtmp1
-rw-r-----. 1 mysql mysql 12582912 Nov 28 17:05 ibtmp1

案例2:

mysql> create table orders ( o_orderkey int(11) not null,o_custkey int(11) default null,o_orderstatus char(1) default null,o_totalprice double default null,o_orderDATE date default null, o_clerk char(15) default null, o_orderpriority char(15) default null, o_comment varchar(79) default null,primary key (o_orderkey),key `i_o_custkey`(`o_custkey`));
Query OK, 0 rows affected (0.23 sec)

mysql> show create table orders\G
*************************** 1. row ***************************
Table: orders
Create Table: CREATE TABLE `orders` (
`o_orderkey` int(11) NOT NULL,
`o_custkey` int(11) DEFAULT NULL,
`o_orderstatus` char(1) DEFAULT NULL,
`o_totalprice` double DEFAULT NULL,
`o_orderDATE` date DEFAULT NULL,
`o_clerk` char(15) DEFAULT NULL,
`o_orderpriority` char(15) DEFAULT NULL,
`o_comment` varchar(79) DEFAULT NULL,
PRIMARY KEY (`o_orderkey`),
KEY `i_o_custkey` (`o_custkey`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

mysql> show table status like 'orders'\G 查看表的状态
*************************** 1. row ***************************
Name: orders
Engine: InnoDB
Version: 10
Row_format: Dynamic
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 16384
Data_free: 0
Auto_increment: NULL
Create_time: 2017-11-28 17:24:22
Update_time: NULL
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)

二、外键约束

[CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) reference_definition | CHECK (expr)

reference_definition:
  REFERENCES tbl_name (index_col_name,...)
  [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]
  [ON DELETE reference_option]
  [ON UPDATE reference_option]

reference_option:

  RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT

RESTRICT: 严格模式,当删除父表的某条记录,但子表还有引用该条记录的字段,是不能删除的

CASCADE:级联(如果主表的某字段更新咯,那么引用该主表字段的相应从表上的这个字段也会发生更新)

NO ACTION:  相当于CASCADE

  

案例1:

mysql> create table parent ( id int(11) not null,primary key(id))engine=innodb default charset=latin1;
Query OK, 0 rows affected (0.12 sec)

mysql> create table child( id int(11) default null, parent_id int(11) default null,key `par_id`(`parent_id`),constraint `child_ibfk_1` foreign key (`parent_id`) references parent (id) on delete cascade on update cascade);
Query OK, 0 rows affected (0.13 sec)

mysql> insert into parent values(1);
Query OK, 1 row affected (0.02 sec)

mysql> insert into child values (1,1);
Query OK, 1 row affected (0.05 sec)

mysql> update parent set id=2 where id=1;
Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from child;
+------+-----------+
| id | parent_id |
+------+-----------+
| 1 | 2 |
+------+-----------+
1 row in set (0.00 sec)

(级别更新,on delete cascade on update cascade 只要父表发生变化,所引用的子表也会发生更新)

mysql> alter table child add foreign key (parent_id) references parent (id) on delete no action on update cascade;
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> show create table child\G
*************************** 1. row ***************************
Table: child
Create Table: CREATE TABLE `child` (
`id` int(11) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
KEY `par_id` (`parent_id`),
CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

方法二:CREATE TABLE ... LIKE Syntax

根据目前已经存在的表结构,创建一个空表,该空表包括括原始表中定义的任何列属性和索引

注意:使用与原始表相同的表存储格式创建副本。在原始表中需要SELECT权限。

mysql> create table c like b;
Query OK, 0 rows affected (0.15 sec)

mysql> desc c;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> desc b;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

第三种:CREATE TABLE ... SELECT语法

请注意,SELECT语句中的列 将附加到表格的右侧,而不会与其重叠。以下面的例子:

案例:

mysql> create table foo ( n tinyint);
Query OK, 0 rows affected (0.16 sec)

mysql> insert into foo select 1;
Query OK, 1 row affected (0.01 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> create table bar (m int) select n from foo; (n列是附加在m列之后)
Query OK, 1 row affected (0.10 sec)
Records: 1 Duplicates: 0 Warnings: 0

mysql> select * from bar;
+------+------+
| m | n |
+------+------+
| NULL | 1 |
+------+------+
1 row in set (0.00 sec)

二、Alter table 更新表

1、添加外键

ADD [CONSTRAINT [symbol]]
FOREIGN KEY [index_name] (index_col_name,...)
reference_definition

mysql> alter table a add column beizhu blob;

(添加单个字段)

mysql> alter table child add foreign key (parent_id) references parent (id) on delete no action on update cascade;(添加多个字段)
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> show create table child\G
*************************** 1. row ***************************
Table: child
Create Table: CREATE TABLE `child` (
`id` int(11) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
KEY `par_id` (`parent_id`),
CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

2、删除字段

mysql> alter table a drop column username;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0

3、重命名表

mysql> create table t1 ( a int,b char(10));
Query OK, 0 rows affected (0.16 sec)

mysql> alter table t1 rename t2;  (RENAME)
Query OK, 0 rows affected (0.03 sec)

mysql> desc t1;
ERROR 1146 (42S02): Table 'testDB.t1' doesn't exist
mysql> desc t2;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| a | int(11) | YES | | NULL | |
| b | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.01 sec)

4、modify修改列的属性值 (不更改表字段名)

MODIFY [COLUMN] col_name column_definition

mysql> alter table t2 modify a tinyint not null;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc t2;
+-------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------+------+-----+---------+-------+
| a | tinyint(4) | NO | | NULL | |
| b | char(10) | YES | | NULL | |
+-------+------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

4、change修改列的属性(更改表字段名,例如把原来的b改成c)

CHANGE [COLUMN] old_col_name new_col_name column_definition

mysql> alter table t2 change b c varchar(20);
Query OK, 0 rows affected (0.15 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc t2;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| a | tinyint(4) | NO | | NULL | |
| c | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

5、添加新的字段

| ADD [COLUMN] col_name column_definition
[FIRST | AFTER col_name]
| ADD [COLUMN] (col_name column_definition,...)

mysql> alter table t2 add column d timestamp;
Query OK, 0 rows affected (0.12 sec)
Records: 0 Duplicates: 0 Warnings: 0

6、添加索引

| ADD {INDEX|KEY} [index_name]
[index_type] (index_col_name,...) [index_option] ...
| ADD [CONSTRAINT [symbol]] PRIMARY KEY
[index_type] (index_col_name,...) [index_option] ...
| ADD [CONSTRAINT [symbol]]
UNIQUE [INDEX|KEY] [index_name]
[index_type] (index_col_name,...) [index_option] ...
| ADD FULLTEXT [INDEX|KEY] [index_name]
(index_col_name,...) [index_option] ...
| ADD SPATIAL [INDEX|KEY] [index_name]
(index_col_name,...) [index_option] ...

mysql> alter table t2 add index (d);

mysql> alter table t2 add primary key (a); (添加主键)
Query OK, 0 rows affected (0.15 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> alter table t2 add unique (c); (添加唯一键)
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0

7、删除类

| DROP [COLUMN] col_name 删除列表
| DROP {INDEX|KEY} index_name 删除索引
| DROP PRIMARY KEY 删除主键
| DROP FOREIGN KEY fk_symbol 删除外键

mysql> alter table t2 drop primary key;
Query OK, 0 rows affected (0.15 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc t2;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| a | tinyint(4) | NO | | NULL | |
| c | varchar(20) | YES | UNI | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> alter table t2 add index t2_index_name (name);
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc t2;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| a | tinyint(4) | NO | | NULL | |
| c | varchar(20) | YES | UNI | NULL | |
| age | tinyint(4) | YES | | NULL | |
| name | tinyint(4) | YES | MUL | NULL | |
| sex | enum('meil','fimile') | YES | | NULL | |
+-------+-----------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> alter table t2 drop index t2_index_name;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc t2;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| a | tinyint(4) | NO | | NULL | |
| c | varchar(20) | YES | UNI | NULL | |
| age | tinyint(4) | YES | | NULL | |
| name | tinyint(4) | YES | | NULL | |
| sex | enum('meil','fimile') | YES | | NULL | |
+-------+-----------------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

8、要将此表转换为基于磁盘的存储,可以使用以下ALTER TABLE语句:

InnoDB and Online DDL

官网:https://dev.mysql.com/doc/refman/5.7/en/innodb-online-ddl.html

MySQL表的创建与维护的更多相关文章

  1. Django之集合函数使用与mysql表的创建特殊字段分析

    1. 集合函数的使用场景: -- 单独使用: 不分组, 只查聚合结果 -- 分组使用: 按字段分组, 可查询分组字段与聚合结果 2. 导入聚合函数 from django.db.models impo ...

  2. MySQL表的创建和表中数据操作

    这篇文章主要介绍在navicat的命令界面操作mysql.主要涉及建立表结构,和对表中数据的增加删除修改查询等动作.站在一个新手角度的简单mysql表结构和数据操作. ☆ 准备工作 1,保证自己的电脑 ...

  3. mysql表的创建、查看、修改、删除

    一.创建表 创建表前先使用use 数据库名进入某一个数据库,创建表语句的格式如下: create table 表名称 ( 列名1 列的数据类型 [约束], 列名2 列的数据类型 [约束], 列名2 列 ...

  4. mysql表的创建和删除

    在创建数据库表时,最好是在编辑器中写好创建表的代码,然后粘贴到命令行中,这样如果有错修改起来方便. 现在来创建一个user表: -- 打开数据库, --后面必须要有空格, 表示注释 USE mydb3 ...

  5. MySQL表的创建

    第1步:设计 首先要设计一张用于我想要用途的表,例如如下用于描述个人的信息类型: 姓名: 性别: 出生日期: 地址: 最喜爱的食物. 下面为他来指定列和数据类型: 列 | 类型 | 允许值 | - | ...

  6. MySQL 表的创建、修改、删除

    1.创建表 create table 表名 ( 列名 类型 是否可以为空 列名 类型 是否可以为空 ) engine=innodb default charset=utf8; 是否可以为控制.null ...

  7. MSSQL → 04:表的创建与维护

    一.创建表 1.1.使用SQL Server Management Studio创建表 ①.打开刚刚建立的CollegeSystemDB数据库,找到表(数据库->CollegeSystemDB- ...

  8. PHP 创建 MySQL 表

    CREATE TABLE 语句用于创建 MySQL 表. 创建表前,我们需要使用 use myDB 来选择要操作的数据库: use myDB; 我们将创建一个名为 "MyGuests&quo ...

  9. Django之mysql表单操作

    在Django之ORM模型中总结过django下mysql表的创建操作,接下来总结mysql表记录操作,包括表记录的增.删.改.查. 1. 添加表记录 class UserInfo(models.Mo ...

随机推荐

  1. 通用mapper接口已经写好的 根据 list 集合查询 相应数据

    package tk.mybatis.mapper.additional.idlist; import org.apache.ibatis.annotations.Param; import org. ...

  2. rsync 应用总结

    rysnc server端 1.vim /etcrsyncd.conf (用户rsync,目录,模块,非系统虚拟用户及密码文件) 2.创建共享目录 /data/www/{www,bbs,blog} 3 ...

  3. 算法之暴力破解和kmp算法 判断A字符串是否包含B字符串

    我们都知道java中有封装好的方法,用来比较A字符串是否包含B字符串 如下代码,contains,用法是 str1.contains(str2), 这个布尔型返回,存在返回true,不存在返回fals ...

  4. Linux教程 Find命令的使用

    Linux中的Find(查找)命令是在Linux系统中最重要并且更有用的命令之一.Find命令主要用于指定匹配文件条件的参数查找或者定位文件和目录的列表.Find命令能够被使用基于各种各样的条件,例如 ...

  5. 0010Springboot整合thymeleaf

    1.pom.xml中添加thymeleaf的起步依赖 2.编写html文件并放在classpath:/templates/路径下 3.编写controller并返回字符串,会到classpath:/t ...

  6. mysql 5.7 版本 You must reset your password using ALTER USER statement before executing this statement报错处理

    https://blog.csdn.net/muziljx/article/details/81541896 MySQL版本5.7.6版本开始的用户可以使用如下命令: mysql> ALTER ...

  7. python_网络编程hmac模块验证客户端的合法性

    hmac模块: 比较两个函数的密钥是否一致: import hmac import os msg = os.urandom(32) #生成32位随机字节码 def wdc(): key = b'wdc ...

  8. 2020即将到来!DevExpress Winforms开发有哪些新功能值得期待?

    下载DevExpress v19.2完整版 DevExpress Winforms Controls 内置140多个UI控件和库,完美构建流畅.美观且易于使用的应用程序.DevExpress Winf ...

  9. 检测 gcc 是否支持 C99 标准的方法

    一般来说 gcc 3.0 以上都是支持 C99 的 但是编译的时候得加上 -std=c99 检测 gcc 是否支持 C99 方法,新建 c99.c 文件,内容如下 #include <stdio ...

  10. pandas实现hive的lag和lead函数 以及 first_value和last_value函数

    lag和lead VS shift 该函数的格式如下: 第一个参数为列名, 第二个参数为往上第n行(可选,默认为1), 第三个参数为默认值(当往上第n行为NULL时候,取默认值,如不指定,则为NULL ...