MySQL
临时表在我们需要保存一些临时数据
时是非常有用的。临时表只在当前连接可见,当关闭连接时,Mysql
会自动删除表并释放所有空间.
实例:
创建一个临时表
CREATE TEMPORARY TABLE SalesSummary (
product_name VARCHAR(50) NOT NULL,
total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00,
avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00,
total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
删除临时表
DROP TABLE SalesSummary;
步骤如下:
SHOW CREATE TABLE
命令获取创建数据表(CREATE TABLE)
语句,该语句包含了原数据表的结构,索引等。SQL
语句,修改数据表名,并执行SQL
语句,通过以上命令 将完全的复制数据表结构。INSERT INTO ... SELECT
语句来实现。mysql> show create table orders \G;
*************************** 1. row ***************************
Table: orders
Create Table: CREATE TABLE `orders` (
`pId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`orderNo` int(10) NOT NULL,
`custNo` int(10) NOT NULL,
`orderDate` date DEFAULT NULL,
`delivDate` date DEFAULT NULL,
`submission_date` date DEFAULT NULL,
PRIMARY KEY (`pId`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
SQL
语句,修改表名CREATE TABLE `orders_clone` (
`pId` int(10) unsigned NOT NULL AUTO_INCREMENT,
`orderNo` int(10) NOT NULL,
`custNo` int(10) NOT NULL,
`orderDate` date DEFAULT NULL,
`delivDate` date DEFAULT NULL,
`submission_date` date DEFAULT NULL,
PRIMARY KEY (`pId`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO ordersClone(
pId,
orderNo,
custNo,
orderDate,
delivDate,
submission_date)
SELECT
pId,
orderNo,
custNo,
orderDate,
delivDate,
submission_date
FROM orders;
另一种完整复制表的表
CREATE TABLE ordersClone LIKE orders;
INSERT INTO ordersClone SELECT * FROM orders;
拷贝一个表中其中一些字段
CREATE TABLE orders2 AS
(
SELECT pId, orderNo FROM orders
);
可以将新建的表的字段改名:
CREATE TABLE orders3 AS
(
SELECT pId, orderNo AS order3No, custNo AS cust3No FROM orders
);
可以拷贝一部分数据:
CREATE TABLE orders4 AS
(
SELECT * FROM orders WHERE orderNo = 22
);
可以在创建表的同时定义表中的字段信息:
CREATE TABLE orders5
(
pId INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY
)
AS
(
SELECT * FROM orders
);