SQL基础语法—create语句

Create 语句

Create database语句

create database 语句是在MySQL实例上创建一个指定名的数据库,create schema语句的语义和create database是一样的。先来看下create的语法:

Syntax:
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
    [create_specification] ...

create_specification:
    [DEFAULT] CHARACTER SET [=] charset_name
  | [DEFAULT] COLLATE [=] collation_name
  • 当创建的数据库本身存在而且没有写明if not exists子句时,则创建数据库的语句会报错,实例如下:
  • create_specification子句指明创建的数据库的属性,并存储在db.opt文件中’
    • character set属性指明此数据库的默认字符集
    • collate属性指明此数据库的默认排序规则
  • 创建后的数据库在数据文件所在的目录会创建一个与数据库名相同的文件目录,用来包含后续创建的表文件;
  • 当然,也可以直接通过mkdir的操作系统命令在数据目录创建文件夹,则MySQL会识别为一个数据库,并在执行show databases命令时可以看到。

创建数据示例如下:

  • 通过在data目录下创建目录来创建数据库:
    注意:8.0版本中不支持通过这种 方式创建数据库。

  • 使用create database创建数据库:

mysql> create database test;    ##创建数据库成功
Query OK, 1 row affected (0.08 sec)

mysql> create database test;    ##再次创建数据库失败
ERROR 1007 (HY000): Can't create database 'test'; database exists
mysql> create database if not exists test;  ##语句执行成功
Query OK, 1 row affected, 1 warning (0.01 sec)

mysql> use test;    ##切换到test数据库
Database changed

Create table语句

create table语句是在数据库中创建表。在MySQL实例中可以 通过? create table方式来查看其语法:

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) }

创建表的三种方式详解

  • table_name表示被创建的表名,默认在当前数据库下创建此表,当然也可以指定在某个数据库下创建表;
  • if not exists表示当相同的表名存在是,则不执行此创建语句,避免语句执行错误
mysql> use test;
Database changed
mysql> create table student(sid int,sname varchar(10));  
Query OK, 0 rows affected (0.11 sec)

mysql> show create table student;
+---------+-----------------------------------------------------------------------------------           ---------------------------------------------------------------------------+
| Table   | Create Table                                                                                                                                                            |
+---------+-----------------------------------------------------------------------------------           ---------------------------------------------------------------------------+
| student | CREATE TABLE `student` (
  `sid` int(11) DEFAULT NULL,
  `sname` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------+-----------------------------------------------------------------------------------           ---------------------------------------------------------------------------+
1 row in set (0.07 sec)

mysql> create table test1.student(sid int,sname varchar(10));  ##在test1数据库下创建student表
Query OK, 0 rows affected (0.15 sec)
mysql> create table if not exists student(sid int,sname varchar(10));
  • temporary关键词表示创建的是临时表,临时表仅对本次登陆MySQL实例的用户可见,另外的数据库连接不可见。当本连接断开时,临时表也会被drop掉。
mysql> create temporary table temp1(sid int,sname varchar(10));
Query OK, 0 rows affected (0.00 sec)

mysql> insert into temp1 values(1,'a');
Query OK, 1 row affected (0.01 sec)

mysql> select * from temp1;
+------+-------+
| sid  | sname |
+------+-------+
|    1 | a     |
+------+-------+
1 row in set (0.00 sec)
##另一个数据库连接执行相同的查询语句查不到数据
mysql> select * from temp1;
ERROR 1146 (42S02): Table 'test.temp1' doesn't exist
##本数据库连接断开后再连接,临时表也不存在
mysql> select * from temp1;
ERROR 1046 (3D000): No database selected
  • like关键词表示基于另外一个表的定义赋值一个新的空表。空表上的字段属性和索引都和原表相同
mysql> create table students_copy like student;
Query OK, 0 rows affected (0.04 sec)

mysql> show create table students_copy;
+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table         | Create Table                                                                                                                                                       |
+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| students_copy | CREATE TABLE `students_copy` (
  `sid` int(11) DEFAULT NULL,
  `sname` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

##验证like关键在创建表时只复制原表的字段信息,不复制表中的内容

##删除students_copy表
mysql> drop table students_copy;
Query OK, 0 rows affected (0.13 sec)

##修改stedent表名为students
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| student        |
+----------------+
1 row in set (0.00 sec)

mysql> alter table student rename to students;
Query OK, 0 rows affected (0.06 sec)

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


##给students表添加一个gender int字段
mysql> alter table students add(gender int);
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> desc students;
+--------+-------------+------+-----+---------+-------+
| Field  | Type        | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sid    | int(11)     | YES  |     | NULL    |       |
| sname  | varchar(10) | YES  |     | NULL    |       |
| gender | int(11)     | YES  |     | NULL    |       |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

##修改students表的字段属性,sname不能为空,sid为主键
mysql> alter table students modify sname varchar(20) not null;
Query OK, 0 rows affected (0.01 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table students add primary key(sid);
Query OK, 0 rows affected (0.04 sec)
Records: 0  Duplicates: 0  Warnings: 0

##给students表中的sname字段创建一个索引
mysql> create index idx_1 on students(sname);  
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table students;
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                           |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| students | CREATE TABLE `students` (
  `sid` int(11) NOT NULL,
  `sname` varchar(20) NOT NULL,
  `gender` int(11) DEFAULT NULL,
  PRIMARY KEY (`sid`),
  KEY `idx_1` (`sname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

##使用like关键创建一个students_copy表
mysql> insert into students values(1,'viktor',1);  ##在students表中插入一条数据
Query OK, 1 row affected (0.07 sec)

mysql> select * from students;
+-----+--------+--------+
| sid | sname  | gender |
+-----+--------+--------+
|   1 | viktor |      1 |
+-----+--------+--------+
1 row in set (0.00 sec)

mysql> create table students_copy like students;
Query OK, 0 rows affected (0.03 sec)

mysql> show create table students_copy;
+---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table         | Create Table                                                                                                                                                                                                                                |
+---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| students_copy | CREATE TABLE `students_copy` (
  `sid` int(11) NOT NULL,
  `sname` varchar(20) NOT NULL,
  `gender` int(11) DEFAULT NULL,
  PRIMARY KEY (`sid`),
  KEY `idx_1` (`sname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

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

  • create table ... as select语句表示创建表的同时将select的查询结果数据插入到表中,但索引和主外键信息都不会同步过来
mysql> create table students_copy2 as select * from students where sid=1;
Query OK, 1 row affected (0.09 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> show create table students_copy2;
+----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table          | Create Table                                                                                                                                                                                 |
+----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| students_copy2 | CREATE TABLE `students_copy2` (
  `sid` int(11) NOT NULL,
  `sname` varchar(20) NOT NULL,
  `gender` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+----------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> select * from students_copy2;
+-----+--------+--------+
| sid | sname  | gender |
+-----+--------+--------+
|   1 | viktor |      1 |
+-----+--------+--------+
1 row in set (0.00 sec)

mysql> create table students_copy3 as select sid,sname from students where sid = 1;
Query OK, 1 row affected (0.10 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> desc students_copy3;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid   | int(11)     | NO   |     | NULL    |       |
| sname | varchar(20) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

create table的其他选项

  • ignorereplace表示在插入数据的过程中如果新表中碰到违反唯一约束的情况下怎么处理,ignore表示不插入,replace表示替换已有的数据,默认两个关键词都不写则碰到违反的情况会报错
  • data_type表示定义的字段类型
  • not null/null表示字段是否允许为空,默认为null表示允许为空,not null表示需要对此字段明确数值,或者要有默认值,否则报错
mysql> create table student2(sid int not null,sname varchar(20));
Query OK, 0 rows affected (0.08 sec)

mysql> insert into student2(sname) values('dabric');
ERROR 1364 (HY000): Field 'sid' doesn't have a default value
  • default表示设置字段的默认值
mysql> create table student3(sid int not null,sname varchar(10),gender int default 0);
Query OK, 0 rows affected (0.05 sec)

mysql> insert into student3 values(1,'tom',default);
Query OK, 1 row affected (0.08 sec)

mysql> insert into student3(sid,sname) values(1,'jerry');
Query OK, 1 row affected (0.10 sec)

mysql> select * from student3;
+-----+-------+--------+
| sid | sname | gender |
+-----+-------+--------+
|   1 | tom   |      0 |
|   1 | jerry |      0 |
+-----+-------+--------+
2 rows in set (0.00 sec)
  • auto_increment表示字段为整数或者浮点数类型的value+1递增数值,value为当前表中该字段最大的值,默认是从1开始递增;一个表中只容许有一个自增字段,且该字段必须有key属性,不能含有default属性,且踹负值会被当成很大的正数

  • column_format目前仅在ndb存储引擎的表上有用,表示该字段的存储类型是fixeddynamic或者default

  • storage 目前也仅在ndb存储引擎的表上有用

  • constraint表示为主键、唯一键、外键等约束条件命名,如果没有命名则MySQL会默认给一个

  • primary_key表示该字段为主键,主键字段必须唯一,必须非空,一个表中只能有一个主键,主键可以包含一个或多个字段

  • key/index表示索引字段

  • unique表示该字段为唯一属性字段,且允许包含多个null

mysql> show create table students;
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                           |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| students | CREATE TABLE `students` (
  `sid` int(11) NOT NULL,
  `sname` varchar(20) NOT NULL,
  `gender` int(11) DEFAULT NULL,
  PRIMARY KEY (`sid`),
  KEY `idx_1` (`sname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+----------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

##创建sid字段索引的unique
mysql> create unique index idx_2 on students(sid);
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> create unique index idx_3 on students(sname);
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

##多个字段的unique,必须保证两个字段叠加在一起不重复
mysql> create unique index idx_4 on students(sid,sname);
Query OK, 0 rows affected (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> show create table students;
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                                                                                                               |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| students | CREATE TABLE `students` (
  `sid` int(11) NOT NULL,
  `sname` varchar(20) NOT NULL,
  `gender` int(11) DEFAULT NULL,
  PRIMARY KEY (`sid`),
  UNIQUE KEY `idx_2` (`sid`),
  UNIQUE KEY `idx_3` (`sname`),
  UNIQUE KEY `idx_4` (`sid`,`sname`),
  KEY `idx_1` (`sname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
  • foreign key表示该字段为外键字段
    • 如果某个字段是另一个表中的字段的外键,在删除这条数据时,得先删除和外键相关的那条数据
mysql> create table 'gender'(
    gender_id int(11) not null,
    name varchar(10) default null,
    primary key (gender_id)
)
mysql> create student5(sid int not nll primary key auti_increment,sname varchar(10) unique,gender int,constraint for_1 foreign key(gender) references gender(gender_id))

案例练习

​ 设计一个学生选课数据库系统

  • 创建一个名为course的数据库
  • 在该数据库下创建一下几个表:

    • student表:sid整型自增主键,sname字符串64位,gender字符串12位,dept_id整型并外键到dept表的id字段

    • dept表:id整型自增主键,dept_name字符串64位

    • course表:id整型自增字段主键,course_name字符串64位,teacher_id整型外键到teacher表的id字段

    • teacher表:id整型自增字段主键,name字符创64位,dept_id整型外键到dept表的id字段
  • students表和teacher表的dept_id为非空

上一篇:数据库关系概念作业


下一篇:第四章 数据查询(上)