sql 从现有数据创建表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 从现有数据创建表相关的知识,希望对你有一定的参考价值。

-- Duplicate the structure of a table:
CREATE TABLE artist_2 LIKE artist; -- create table 'artist_2', with indentical structure to table 'artist', no data

-- Create a table and copy some data:
CREATE TABLE artist_2 SELECT * FROM artist; -- completely identical table now

-- Create a table with data from multiple other tables:
-- example - 'report' table that contains names of artists and their albums:
CREATE TABLE report (artist_name CHAR(128), album_name CHAR(128)) -- not duplicating structure
SELECT artist_name, album_name FROM artist INNER JOIN album -- data copied from artist and album
USING (artist_id);

\!h NOTE: a query like this won't copy indexes(keys), to do so:
-- use LIKE to create an empty table with the indexes, then copy data using INSERT with SELECT.
-- or:
-- CREATE TABLE with a SELECT statement, then add indexes using ALTER TABLE.
-- or:
-- Use the UNIQUE(or PRIMARY KEY, or KEY) keyword, in combination with the CREATE TABLE and SELECT stament:
CREATE TABLE artist_2 (UNIQUE(artist_id)) -- PRI key is now artist_id
SELECT * FROM artist;

\!h Anything you can do in a regular CREATE TABLE statement, you can do in this variant
-- this includes DEFAULT, NULL, PRIMARY KEY settings etc:
CREATE TABLE artist_3
(artist_id SMALLINT(5), NOT NULL AUTO_INCREMENT,
artist_name CHAR(128) NOT NULL DEFAULT "New Order",
PRIMARY KEY (artist_id), KEY(artist_name))
SELECT * FROM artist;

以上是关于sql 从现有数据创建表的主要内容,如果未能解决你的问题,请参考以下文章

使用 Query 为现有表生成 SQL 创建脚本

创建 SQL 表作为现有表的副本(ODBC 和 C#)[关闭]

如何从现有 SQL DB ASP.Net MVC 4 在下拉列表中填充数据

创建没有重复的新 SQL 表

如何为 PL SQL 中的现有表创建唯一 ID?

使用 MS Access SQL 查询创建与现有表具有一对一关系的第二个表