目前,我在sql server中有这个代码,它应该从数据库中获取值并将它们放到另一个数据库中。
Insert into AppleFinalX.[dbo].SalesFactTable(SalesType, TotalSales, SalesHDRDate, ProductSales, ProductID)
SELECT AppleFinal.[dbo].SalesHDRTable.SalesType,
AppleFinal.[dbo].SalesHDRTable.TotalSales,
AppleFinal.[dbo].SalesHDRTable.SalesHDRDate,
AppleFinal.[dbo].SalesDetailsTable.PurchaseAmount,
AppleFinal.[dbo].ProductTable.ProductID
FROM AppleFinal.[dbo].SalesHDRTable,
AppleFinal.[dbo].SalesDetailsTable,
AppleFinal.[dbo].ProductTable
基本上,它从不同数据库(AppleFinal)的三个表中获取值,并将它们放在不同数据库(AppleFinalX)的表中。但不幸的是,它返回1000条记录而不是10条。任何人都知道为什么会这样? :(所有表格各有10条记录,所以我很震惊地看到新表中的1000条记录......
答案 0 :(得分:2)
正如其他人所评论的那样,您将每个表的每一行连接到每个其他表的每一行。那显然不是你想要的。使用JOIN命令是解决方案。像这样:
SELECT AppleFinal.[dbo].SalesHDRTable.SalesType,
AppleFinal.[dbo].SalesHDRTable.TotalSales,
AppleFinal.[dbo].SalesHDRTable.SalesHDRDate,
AppleFinal.[dbo].SalesDetailsTable.PurchaseAmount,
AppleFinal.[dbo].ProductTable.ProductID
FROM AppleFinal.[dbo].SalesHDRTable
INNER JOIN AppleFinal.[dbo].SalesDetailsTable
ON AppleFinal.[dbo].SalesHDRTable.ID = AppleFinal.[dbo].SalesDetailsTable.SalesID
INNER JOIN AppleFinal.[dbo].ProductTable
ON AppleFinal.[dbo].SalesDetailsTable.ProductID = AppleFinal.[dbo].ProductTable.ID
答案 1 :(得分:0)
明确说明你的连接要好得多:
INSERT INTO AppleFinalX.dbo.SalesFactTable
(SalesType, TotalSales, SalesHDRDate, ProductSales, ProductID)
SELECT sh.SalesType,
sh.TotalSales,
sh.SalesHDRDate,
sd.PurchaseAmount,
pt.ProductID
FROM AppleFinal.dbo.SalesHDRTable sh
LEFT JOIN AppleFinal.dbo.SalesDetailsTable sd ON sd.saleType = sh.saleType
LEFT JOIN AppleFinal.dbo.ProductTable pt ON pt.ProductID = sh.ProductID
答案 2 :(得分:0)
虽然我更愿意申请必要的加入,但也试试这个:
Insert into AppleFinalX.[dbo].SalesFactTable(SalesType, TotalSales, SalesHDRDate, ProductSales, ProductID)
SELECT AppleFinal.[dbo].SalesHDRTable.SalesType,
AppleFinal.[dbo].SalesHDRTable.TotalSales,
AppleFinal.[dbo].SalesHDRTable.SalesHDRDate,
AppleFinal.[dbo].SalesDetailsTable.PurchaseAmount,
AppleFinal.[dbo].ProductTable.ProductID
FROM AppleFinal.[dbo].SalesHDRTable,
AppleFinal.[dbo].SalesDetailsTable,
AppleFinal.[dbo].ProductTable
group by AppleFinal.[dbo].SalesHDRTable.SalesType,
AppleFinal.[dbo].SalesHDRTable.TotalSales,
AppleFinal.[dbo].SalesHDRTable.SalesHDRDate,
AppleFinal.[dbo].SalesDetailsTable.PurchaseAmount,
AppleFinal.[dbo].ProductTable.ProductID