插入引用另一个表的值
Posted
技术标签:
【中文标题】插入引用另一个表的值【英文标题】:Insert values referring to another table 【发布时间】:2019-01-22 15:35:51 【问题描述】:我创建了以下简单的datamodel
:
我使用以下insert statements
插入值:
1) 表产品:
INSERT INTO test.products
(ProductName, Price)
VALUES
("Product A","99,99"),
("Product B","49,95"),
("Product C","5,95");
2) 表格订单:
INSERT INTO test.orders
(Customer)
VALUES
("Customer A"),
("Customer B"),
("Customer B");
到目前为止,这一切都很好。
但是,现在我还想将值插入到表 Products_per_Order
中。
正如您在datamodel
中看到的,Products_per_Order
表包含Price
列。在此列中,我想在Products_idProducts
列中插入引用ID 的价格。因此,我尝试使用以下insert statement
,但到目前为止无法使其工作:
INSERT INTO test.products_per_order
(Orders_idOrders, Products_idProducts, Price, Quantity)
VALUES
("1","1",(Select Price from test.products),"5"),
("1","2",(Select Price from test.products),"4"),
("2","1",(Select Price from test.products),"10"),
("3","2",(Select Price from test.products),"3"),
("3","3",(Select Price from test.products),"9");
你知道如何解决这个问题吗?
【问题讨论】:
您的查询毫无意义。 应该为每一行插入哪个价格? 【参考方案1】:您可以使用子查询从 Products 表中提取它。
("2","1","Select Price from test.products where test.products.idProducts = '1')","10");
【讨论】:
【参考方案2】:您很接近,但是当您拥有(Select Price from test.products)
时,您会从 test.products 表中选择所有价格。你需要让它返回一个值。
INSERT INTO test.products_per_order
(Orders_idOrders, Products_idProducts, Price, Quantity)
VALUES
("1","1",(Select Price from test.products WHERE test.products.idProducts = '1'),"5"),
("1","2",(Select Price from test.products WHERE test.products.idProducts = '2'),"4"),
("2","1",(Select Price from test.products WHERE test.products.idProducts = '1'),"10"),
("3","2",(Select Price from test.products WHERE test.products.idProducts = '2'),"3"),
("3","3",(Select Price from test.products WHERE test.products.idProducts = '3'),"9");
【讨论】:
【参考方案3】:我建议改用insert . . . select
:
insert into test.products_per_order (Orders_idOrders, Products_idProducts, Price, Quantity)
select x.idOrder, x.idProduct, p.price, x.qty
from (select 1 as idOrder, 2 as idProduct, 5 as qty union all
select 1 as idOrder, 2 as idProduct, 4 as qty union all
. . . -- I've left these out so you can see the structure of the query
select 3 as idOrder, 3 as idProduct, 9 as qty
) x left join
test.products p
on p.idProducts = x.idProduct;
这大大降低了拼写错误导致错误价格的可能性。
【讨论】:
嗨,戈登,感谢您的回答。工作台在“)x左连接”行向我显示查询有问题(运行语句时我也收到错误代码:1064)。我试图放置,或;在选择语句之后但无法使其工作。 @Michi 。 . . mysql 绝对支持这种语法。也许您在最后一行留下了额外的union all
。
非常感谢。现在它正在工作。我只需要更改“on p.idProduct = x.idProduct;”这一行因为缺少一个 s “on p.idProducts = x.idProduct;”。
嗨,戈登,您对此有什么想法吗:***.com/questions/54350789/…以上是关于插入引用另一个表的值的主要内容,如果未能解决你的问题,请参考以下文章