赞
踩
1. 常规 create table 方式
2. create table2 like table1 方式
3. 根据查询 table1 的结果集来创建表 table2 方式
CREATE TABLE [if not exists] table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
数据类型(data_type)规定了列可容纳何种数据类型。下面的表格包含了SQL中最常用的数据类型:
数据类型 | 描述 |
---|---|
integer(size)、int(size)、smallint(size) tinyint(size) | 仅容纳整数。在括号内规定数字的最大位数。 |
decimal(size,d)、numeric(size,d) | 容纳带有小数的数字。 “size” 规定数字的最大位数。“d” 规定小数点右侧的最大位数。 |
char(size) | 容纳固定长度的字符串(可容纳字母、数字以及特殊字符)。 在括号中规定字符串的长度。 |
varchar(size) | 容纳可变长度的字符串(可容纳字母、数字以及特殊的字符)。 在括号中规定字符串的最大长度。 |
date(yyyymmdd) | 容纳带有小数的数字。 容纳日期。 |
CREATE TABLE if not exists Orders
(
OrderId int(10) NOT NULL AUTO_INCREMENT,//自增ID
ProductName varchar(50) NOT NULL,
OrderDate datetime NOT NULL DEFAULT NOW(),//默认值是当前时间,当向表中插入行时,当前日期和时间自动插入列中。
PRIMARY KEY (OrderId)
);
INSERT INTO Orders (ProductName) VALUES ('Mobile phone');
mysql> SELECT * FROM Orders;
+---------+--------------+---------------------+
| OrderId | ProductName | OrderDate |
+---------+--------------+---------------------+
| 1 | Mobile phone | 2020-01-09 19:06:00 |
+---------+--------------+---------------------+
1 row in set (0.05 sec)
2. create table2 like table1 方式
mysql> CREATE TABLE Orders_new LIKE Orders;
mysql> DESC Orders; +-------------+-------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+-------------------+----------------+ | OrderId | int(10) | NO | PRI | NULL | auto_increment | | ProductName | varchar(50) | NO | | NULL | | | OrderDate | datetime | NO | | CURRENT_TIMESTAMP | | +-------------+-------------+------+-----+-------------------+----------------+ 3 rows in set (0.09 sec) mysql> DESC Orders_new; +-------------+-------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+-------------------+----------------+ | OrderId | int(10) | NO | PRI | NULL | auto_increment | | ProductName | varchar(50) | NO | | NULL | | | OrderDate | datetime | NO | | CURRENT_TIMESTAMP | | +-------------+-------------+------+-----+-------------------+----------------+ 3 rows in set (0.05 sec)
3. 根据查询 table1 的结果集来创建表 table2 方式
mysql> CREATE TABLE Orders_new1 AS SELECT OrderId, OrderDate FROM Orders; Query OK, 1 row affected (0.37 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM Orders; +---------+--------------+---------------------+ | OrderId | ProductName | OrderDate | +---------+--------------+---------------------+ | 1 | Mobile phone | 2020-01-09 19:06:00 | +---------+--------------+---------------------+ 1 row in set (0.05 sec) mysql> SELECT * FROM Orders_new1; +---------+---------------------+ | OrderId | OrderDate | +---------+---------------------+ | 1 | 2020-01-09 19:06:00 | +---------+---------------------+ 1 row in set (0.06 sec)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。