【问题标题】:Create table from another one with additional parameters使用其他参数从另一个表创建表
【发布时间】:2012-11-20 07:06:33
【问题描述】:

我想从表 'ProjectTable' 创建一个表 'Customer':

CREATE TABLE Customer AS
    (
        SELECT CustCompanyName, CustContactName, CustContactTitle, CustAddress, CustCity, CustRegion, CustPostalCode, CustCountry, CustPhone, CustFax FROM ProjectTable
    );

我需要在此处添加更多内容,因为附加列 'id' 将是主键列,或者 'customer' 将是对另一个表列的引用。该怎么做?

【问题讨论】:

  • 我的想法是创建第三个表,其中包含所有这些额外的列和参数,然后将它与由“ProjectTable”列组成的“客户”连接起来。有人有更好的主意吗?
  • 哪个数据库?您能否为您正在使用的特定数据库添加一个标签?

标签: sql postgresql create-table


【解决方案1】:

您可以使用与 ProjectTable 相同的表结构和相同的数据创建新表,然后您可以添加所需的其他字段:

SELECT CustCompanyName, CustContactName, CustContactTitle, CustAddress, CustCity, CustRegion, 
CustPostalCode, CustCountry, CustPhone, CustFax INTO Customer FROM ProjectTable

ALTER TABLE Customer ADD ID INT IDENTITY(1,1) PRIMARY KEY

ALTER TABLE Customer ADD customer VARCHAR(10)

ALTER TABLE Customer ADD CONSTRAINT Customer_customer_FK FOREIGN KEY ( customer ) REFERENCES MyOtherTable(PKColumn)

【讨论】:

  • 那不是有效的 PostgreSQL DDL。
  • 是的,没错,我的错。是Sql Server sintax,但逻辑应该是一样的。
  • 是的,但我现在知道这个想法,在这种情况下对我来说就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-26
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多