我有一个列order_id来自customer_order表作为customer_order_products
中的FK
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帮助
答案 0 :(得分:0)
如果我理解正确的话,普通的INSERT
就足够了,你可以用一个语句插入多行
INSERT INTO customer_order_products
([order_id], [product_id], [quantity])
VALUES
(1, 20, 3),
(1, 21, 2),
(1, 17, 5);
<强> SQLFiddle 强>
答案 1 :(得分: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