【问题标题】:Import Data to a new table that has a nested table in it将数据导入包含嵌套表的新表
【发布时间】:2015-02-18 20:35:06
【问题描述】:
INSERT INTO OrderNew (
SalesOrderID,
OrderDate,
DueDate,
ShipDate,
OnlineOrderFlag,
CustomerID,
CreditCardID,
SubTotal,
TaxAmt,
Freight,
TotalDue,
OrderInfo.salesorderdetail,
OrderInfo.orderqty ,
OrderInfo.productid, 
OrderInfo.unitprice,
OrderInfo.unitpricediscount,
OrderInfo.linetotal
)
SELECT h."SalesOrderID" , h."OrderDate", h."DueDate", h."ShipDate", h."OnlineOrderFlag", h."CustomerID", h."CreditCardID", h."SubTotal", h."TaxAmt", h."Freight", h."TotalDue", d."SalesOrderDetailID", d."OrderQty", d."ProductID", d."UnitPrice", d."UnitPriceDiscount", d."LineTotal"
FROM "SalesOrderHeader" h
INNER JOIN "SalesOrderDetail" d ON  d."SalesOrderID" = h."SalesOrderID"
WHERE d."SalesOrderID" = h."SalesOrderID" ;

这是我用来从其他一些表中导入数据的代码。 但是,我希望最后一列像一个嵌套表。 这些是我想成为的表。因此,对于“SalesOrderHeader”表中的一个销售订单 ID,在“SalesOrderDetail”表中有几个或多个具有相同销售订单 ID 的记录。那么,我该怎么做呢?使用函数?

我不知道我是否可以理解。但我可以提供更多信息。

【问题讨论】:

  • Postgres 中没有嵌套表这种东西。您将需要创建正确的一对多关系,然后分别插入每个表中。顺便说一句:我强烈建议不要使用带引号的标识符。从长远来看,它们带来的麻烦远多于它们的价值
  • 有没有类似oracle中的create type xyz as table这样的命令?

标签: postgresql insert nested create-table nested-table


【解决方案1】:

您创建两种类型以稍微缩小新表,这将是 SalesOrderHeader 和 SalesOrderDetail 的组合。

CREATE TYPE Shipping AS(OrderDate Date,DueDate Date,ShipDate Date);

CREATE TYPE ordersdetails AS (details text);

然后你创建表。

CREATE TABLE ordernew ( salesorderid serial NOT NULL, shippinginfo shipping, onlineorderflag integer, customerid serial NOT NULL, creditcardid integer, subtotal real, taxamt real, freight real, totaldue real, orderinfo ordersdetails[]);

至于数据,您只需从其他两个表中复制数据,但要编写正确的查询,以免创建重复记录。所以,代码如下。

INSERT INTO OrderNew (
SalesOrderID,
OrderDate,
DueDate,
ShipDate,
OnlineOrderFlag,
CustomerID,CreditCardID,
SubTotal,
TaxAmt,
Freight,
TotalDue,
OrderInfo.salesorderdetail,
OrderInfo.orderqty ,
OrderInfo.productid,
OrderInfo.unitprice,
OrderInfo.unitpricediscount,
OrderInfo.linetotal
)
SELECT h."SalesOrderID" , h."OrderDate", h."DueDate", h."ShipDate", h."OnlineOrderFlag",
h."CustomerID", h."CreditCardID", h."SubTotal", h."TaxAmt", h."Freight", h."TotalDue",
d."SalesOrderDetailID", d."OrderQty", d."ProductID", d."UnitPrice", d."UnitPriceDiscount", d."LineTotal"
FROM "SalesOrderHeader" h
INNER JOIN "SalesOrderDetail" d ON d."SalesOrderID" = h."SalesOrderID"
WHERE d."SalesOrderID" = h."SalesOrderID" ;

要简单地查看您最近插入的数据,只需运行以下查询:

SELECT orderinfo FROM ordernew;

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2022-01-21
    • 2021-11-06
    • 2019-11-10
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多