这是故事:我必须实现过滤器。在这个过滤器中,我过滤了某些类别。其中一个过滤器是“最喜欢的”过滤器(@includeFavourites)。
我有这个带有分页和排序以及一切的庞大 SQL。
现在,当单击过滤器中的“includeFavourites”选项时,我还必须从存储收藏夹的不同表中选择唯一 ID(此条目存储在不同的数据表中)。我试过左外连接,但它为主表中的每条记录返回“收藏夹数”记录。Coalesce 根本没有帮助。
这是我的 SQL:
--this is needed because stored procedure must know how many days are selected
DECLARE @daysCount int
SET @daysCount = 0
IF (@mon IS NOT NULL)
BEGIN
SET @daysCount = @daysCount+1
END
IF (@tue IS NOT NULL)
BEGIN
SET @daysCount = @daysCount+1
END
IF (@wed IS NOT NULL)
BEGIN
SET @daysCount = @daysCount+1
END
IF (@thu IS NOT NULL)
BEGIN
SET @daysCount = @daysCount+1
END
IF (@fri IS NOT NULL)
BEGIN
SET @daysCount = @daysCount+1
END
IF (@sat IS NOT NULL)
BEGIN
SET @daysCount = @daysCount+1
END
IF (@sun IS NOT NULL)
BEGIN
SET @daysCount = @daysCount+1
END
-- Insert statements for procedure here
SELECT * FROM (
SELECT ROW_NUMBER() OVER
(
ORDER BY
CASE WHEN @OrderBy = 'ND' THEN title END DESC,
CASE WHEN @OrderBy = 'NA' THEN title END,
CASE WHEN @OrderBy = '' THEN title END,
CASE WHEN @OrderBy = 'RD' THEN authorRating END DESC,
CASE WHEN @OrderBy = 'RA' THEN authorRating
) AS Row,
Articles.ArticleId, Articles.userId, Articles.timestamp as datePosted, users.screenName,
defaultSmallImagePath, authorRating, ArticleCosts, title,
FROM Articles
LEFT OUTER JOIN
Users on Articles.userId = Users.userId
LEFT OUTER JOIN
ArticleAdditionalInformation ON ArticleAdditionalInformation.ArticleId = Articles.ArticleId
--JOIN FOR CONTINENT
LEFT OUTER JOIN
Codings as Continent ON Continent.codingKeyId = ArticleAdditionalInformation.continentId AND Continent.languageId = @languageId
-- JOIN FOR COUNTRY
LEFT OUTER JOIN
CodingsAssociated as Country ON Country.codingKeyId = ArticleAdditionalInformation.countryId AND Country.languageId = @languageId
-- JOIN FOR Article TRANSLATION DATA
LEFT OUTER JOIN
ArticlesTranslations ON ArticlesTranslations.ArticleId = Articles.ArticleId AND ArticlesTranslations.languageId=@languageId
LEFT OUTER JOIN
ArticleCategories ON ArticleCategories.ArticleId = Articles.ArticleId
WHERE
(
ArticleCategories.categorieId =1 OR ArticleCategories.categorieId =2 OR
ArticleCategories.categorieId =3 OR ArticleCategories.categorieId =4 OR
ArticleCategories.categorieId = 5
) AND
(ArticlesTranslations.title LIKE '%' + @searchString + '%' OR @searchString IS NULL)
-- COST filter
AND
(ArticleCosts < @cost OR @cost = 0)
AND
(ArticleCosts > 0 OR @cost = 0)
--END cost filter
-- EXCLUDE already stored for selected days
AND Articles.ArticleId -- exclude these ArticleIds
NOT IN
(
SELECT DailyContent.ArticleId
FROM DailyContent
WHERE
sectionId=@sectionId AND
(
weekDayId=@mon OR
weekDayId=@tue OR
weekDayId=@wed OR
weekDayId=@thu OR
weekDayId=@fri OR
weekDayId=@sat OR
weekDayId=@sun
)
GROUP BY
DailyContent.ArticleId
HAVING
(COUNT(sectionId) = @daysCount)
)
-- END exclude
) p
WHERE (Row > @startRowIndex AND Row <=@startRowIndex + @pageSize)
ORDER BY Row
END
所以,当@includeFavourites 参数不为空时,我只想包含来自最喜欢的表的唯一articleIds。
任何提示将不胜感激;)
我正在使用 SQL Server 2008。