1

我有两张桌子: 假设在桌子boughtItems(buyerId,ItemId)上每个买家的物品不超过五件。所以我试图将数据从第一个表插入到第二个表中。我正在这样做,从每个买家的第一个表中选择所有行作为denormalized(buyerId,item1,item2,item3,item4,item5)boughtItems

SELECT itemId FROM boughtItems where buyerId=1

然后当读取所有行时,我为第二个表执行相应的插入命令。有什么方法可以加快这个过程吗?如果需要,我也可以发布我的程序代码。

4

1 回答 1

2

注意,你可以只用一个 CTE 来做到这一点,但我认为这很清楚。请记住,我没有在服务器上进行测试,因此可能存在错误或拼写错误。

WITH ranked AS
(
    SELECT buyerID, ROW_NUMBER() OVER(PARTITION BY buyerID) AS ItemRank
    FROM boughtItems
), allColumns AS
(
   SELECT buyerID, i1.ItemID as item1, i2.ItemID as item2, i3.ItemID as item3, i4.ItemID as item4, i5.ItemID as item5
   FROM ranked r
   LEFT JOIN boughtItems item1 ON r.buyerID = item1.buyerID and ItemRank = 1
   LEFT JOIN boughtItems item2 ON r.buyerID = item2.buyerID and ItemRank = 2
   LEFT JOIN boughtItems item3 ON r.buyerID = item3.buyerID and ItemRank = 3
   LEFT JOIN boughtItems item4 ON r.buyerID = item4.buyerID and ItemRank = 4
   LEFT JOIN boughtItems item5 ON r.buyerID = item5.buyerID and ItemRank = 5
)
INSERT INTO denormalized (buyerid, item1, item2, item3, item4, item5)
  SELECT buyerid, item1, item2, item3, item4, item5
  FROM allColumns
于 2012-07-21T18:11:48.923 回答