1

我有一列 order_id 来自 customer_order 表作为 FK,customer_order_products其中有 3 列:

  • order_id,
  • product_id
  • quantity.

我想将它们同时插入到一个表中,这样它就会像这样向我们显示 :::

order_id     product_id     quantity
1              20             3
1              21             2
1              17             5

这意味着客户订购了 3 种具有上述数量的不同产品,生成的 order_id 为 1。

我该如何实现这一点。plzzz 需要帮助

4

2 回答 2

0

如果我对您的理解正确,那么 plainINSERT在您的情况下就足够了,并且允许您用一个语句插入多行

INSERT INTO customer_order_products
    ([order_id], [product_id], [quantity])
VALUES
    (1, 20, 3),
    (1, 21, 2),
    (1, 17, 5);

SQLFiddle

于 2013-03-16T06:30:26.790 回答
0
CREATE TABLE dbo.customer_order
 (
  order_id int
  )

CREATE TABLE dbo.customer_order_products 
 (
  product_id int,
  order_id int,
  quantity int
  )  

INSERT dbo.customer_order
VALUES(1)

INSERT dbo.customer_order_products 
VALUES(20, 1, 2),
      (20, 1, 1),
      (21, 1, 1),
      (21, 1, 1),
      (17, 1, 5)

IF OBJECT_ID('tempdb.dbo.#NewTable') IS NOT NULL DROP TABLE dbo.#NewTable
SELECT c.order_id, p.product_id, SUM(quantity) AS quantity
INTO dbo.#NewTable
FROM dbo.customer_order c JOIN dbo.customer_order_products p ON c.order_id =  p.order_id
GROUP BY c.order_id, p.product_id

SELECT *
FROM dbo.#NewTable

结果:

orde_id product_id quantity
1       17         5
1       20         3
1       21         2
于 2013-03-16T08:04:37.377 回答