0

用户选择最喜欢的商场、品牌和行业

我尝试展示对用户喜爱有效的广告系列。

表格:活动(有商场和品牌)、MallCampaign、商场、品牌、部门、用户、收藏夹

例如; 用户选择了X,Y,ZZ:不包括阿迪达斯店)商场;阿迪达斯李维斯维多利亚的秘密品牌;鞋业。所以用户应该只看到在X,Y商场有效的Adidas的活动。

如何组合这些查询?我应该使用 JOIN 还是 IF EXIST?

    SELECT mc.CampaignId, c.CampaignTitle
    FROM MallCampaign mc 
    JOIN Mall m ON m.MallId = mc.MallId
    JOIN Campaign c ON c.CampaignId = mc.CampaignId
    JOIN Brand b ON b.BrandId = c.BrandId


    SELECT FavoriteItemId AS FavoriteMalls
    FROM Favorite
    WHERE UserId = @UserId AND FavoriteItemType=1 

    SELECT FavoriteItemId AS FavoriteBrands
    FROM Favorite
    WHERE UserId = @UserId AND FavoriteItemType=3 

    SELECT FavoriteItemId AS FavoriteSectors
    FROM Favorite
    WHERE UserId = @UserId AND FavoriteItemType=2 
4

1 回答 1

0

我建议您使用in

SELECT mc.CampaignId, c.CampaignTitle
FROM MallCampaign mc 
where mallid in (SELECT FavoriteItemId AS FavoriteMalls
                 FROM Favorite
                 WHERE UserId = @UserId AND FavoriteItemType=1
                ) and
      brandId in (SELECT FavoriteItemId AS FavoriteBrands
                  FROM Favorite
                  WHERE UserId = @UserId AND FavoriteItemType=3
                 ) and
      sectorid in (SELECT FavoriteItemId AS FavoriteSectors
                   FROM Favorite
                   WHERE UserId = @UserId AND FavoriteItemType=2 
                  )

这阐明了查询的意图。而且,如果你有一个索引,Favorite(UserId, FavorteItemType, FavoriteItemId)性能应该是相当不错的。

于 2013-08-04T15:48:31.730 回答