我有一张这样的表:
| Name | Parent Id | Pricing Id | Paper Id |
|------------------------------------------|
| | | | |
我要插入。问题是,客户不知道ID,只知道父/定价/纸张表中名称字段的值:
| Name | Parent Id | Pricing Id | Paper Id |
|------------------------------------------|
|Narnia| Movies | MidTier | Film |
|Transf| Movies | HighTier | Comic |
Movies
,MidTier
/ HighTier
和Film
/ Comic
需要转换为整数...这里的伪查询:
INSERT INTO products (Name, ParentId, PricingId, PaperId)
VALUES (
"Narnia",
SELECT id FROM categories WHERE Name="Movies",
SELECT id FROM pricing WHERE Name="MidTier",
SELECT id FROM papers WHERE Name="Film"
)
显然这不起作用,但这样做的正确方法是什么?
编辑:请注意,效率并非超高优先级,因为这将是一次性导入(数十万种产品)。
答案 0 :(得分:0)
假设这三个表不能连接在一起,您可以为不同的ID定义变量
DECLARE @categoryId INT,
@pricingId INT,
@papersId INT
SELECT @categoryId = id FROM categories WHERE Name="Movies",
SELECT @pricingId = id FROM pricing WHERE Name="MidTier",
SELECT @papersId = id FROM papers WHERE Name="Film"
INSERT INTO products (Name, ParentId, PricingId, PaperId)
VALUES ('Narnia', @categoryId, @pricingId, @paperId)
但是如果你可以加入这些表并插入如下通用语句之类的值:
INSERT INTO tbl (...)
SELECT t2.id, t3.id
FROM tbl2 as t2
INNER JOIN tbl3 as t3 on t3.id = t2.t3_id
答案 1 :(得分:0)
就个人而言,我更喜欢这些,因为你可以看到究竟会插入什么。要么应该工作。如果性能是一个问题,你应该检查它们,但我更喜欢交叉连接,因为我可以在一个位置看到值的所有内容。我正在使用Narnia的子选择,所以如果我们想插入20个产品,我们可以在子选择中添加一个联合。
INSERT INTO products (Name, ParentId, PricingId, PaperId)
SELECT
Name.Name,c.ID,prc.ID,ppr.ID
FROM (
SELECT 'Narnia' [Name]
) [Name]
CROSS JOIN categories c
CROSS JOIN pricing prc
CROSS JOIN papers ppr
WHERE
c.Name='Movies'
AND prc.Name='MidTier'
AND ppr.Name='Film'
INSERT INTO products (Name, ParentId, PricingId, PaperId)
SELECT
Name.Name,c.ID,prc.ID,ppr.ID
FROM (
SELECT 'Narnia' [Name]
) [Name]
LEFT JOIN categories c ON c.Name='Movies'
LEFT JOIN pricing prc ON prc.Name='MidTier'
LEFT JOIN papers ppr ON ppr.Name='Film'