用户选择喜爱的商场,品牌和行业
我尝试显示对用户的收藏有效的广告系列。
表:Campaign(有商场和品牌),MallCampaign,Mall,Brand,Sector,User,Favorite
例如;用户选择 X,Y,Z ( Z:不包括阿迪达斯商店)商场; 阿迪达斯, Levi's ,维多利亚的秘密品牌; 鞋部门。因此,用户只能看到在 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
答案 0 :(得分: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)
的索引,那么表现应该非常好。