CREATE TABLE AS
語句用於通過複製現有表的列從現有表來建立新表。
注意:如果以這種方式建立表,則新表將包含現有表中的記錄。
語法:
CREATE TABLE new_table
AS (SELECT * FROM old_table);
在此範例中,我們通過複製現有表Customers
中的所有列來建立newcustomers
表。
CREATE TABLE newcustomers
AS (SELECT * FROM customers WHERE customer_id < 5000);
新建立的表命名為newcustomers
並具有與customers
相同的表欄位和記錄(編號小於5000
的所有記錄)。
語法:
CREATE TABLE new_table
AS (SELECT column_1, column2, ... column_n
FROM old_table);
下面來看另一個例子:
CREATE TABLE newcustomers2
AS (SELECT customer_id, customer_name
FROM customers
WHERE customer_id < 5000);
上面的例子將建立一個名為newcustomers2
的新表。 此表包含customers
表中指定的兩列:customer_id
和customer_name
。
語法:
CREATE TABLE new_table
AS (SELECT column_1, column2, ... column_n
FROM old_table_1, old_table_2, ... old_table_n);
下面來看一個例子:假設已經建立了兩個表:regularcustomers
和irregularcustomers
。
regularcustomers
表有三列:rcustomer_id
,rcustomer_name
和rc_city
。
CREATE TABLE "regularcustomers"
( "RCUSTOMER_ID" NUMBER(10,0) NOT NULL ENABLE,
"RCUSTOMER_NAME" VARCHAR2(50) NOT NULL ENABLE,
"RC_CITY" VARCHAR2(50)
)
/
第二個表:irregularcustomers
也有三列:ircustomer_id
,ircustomer_name
和irc_city
。
CREATE TABLE "irregularcustomers"
( "IRCUSTOMER_ID" NUMBER(10,0) NOT NULL ENABLE,
"IRCUSTOMER_NAME" VARCHAR2(50) NOT NULL ENABLE,
"IRC_CITY" VARCHAR2(50)
)
/
在下面的範例中,將建立一個表名:newcustomers3
,從兩個表複製指定列。
範例:
CREATE TABLE newcustomers3
AS (SELECT regularcustomers.rcustomer_id, regularcustomers.rc_city, irregularcustomers.ircustomer_name
FROM regularcustomers, irregularcustomers
WHERE regularcustomers.rcustomer_id = irregularcustomers.ircustomer_id
AND regularcustomers.rcustomer_id < 5000);