从数据库过滤记录

时间:2013-12-13 05:31:12

标签: sql database sql-server-2008 join

我在数据库中有4个表

  1. UsersId, Email, Password, Active
  2. InformationDataId, Title, Description, Link
  3. FiltersId, Keyword, Active
  4. LUserToFilterUserId, FilterId
  5. 现在我想要的是从InformationData表中过滤特定记录,其中标题和描述不包含过滤器表中的关键字,我们根据特定用户ID从LUserToFilter表中选择那些过滤器。

    我尝试了这个查询,但它只返回包含过滤关键字的记录,而不返回其他记录。

    Create Procedure [dbo].[SP_GetFilteredData]
    @userid int
    as
    begin
    select D.* from Filters f
    inner join LUsersToFilters L on L.FilterId=F.Id
    inner join InformationData D on D.Title like '%'+F.KeyWord+'%' or D.Description like '%'+F.KeyWord+'%'
    where L.UserId=@userid
    end
    

    请提出任何建议..

2 个答案:

答案 0 :(得分:1)

SELECT D.* FROM InformationData D
WHERE NOT EXISTS 
   (SELECT * FROM Filters F INNER JOIN LUsersToFilters L ON F.id=L.FilterId
    WHERE (D.Title LIKE '%'+F.KeyWord+'%' OR D.Description LIKE '%'+F.KeyWord+'%')
    AND L.userid = @userid)

答案 1 :(得分:0)

Create Procedure [dbo].[SP_GetFilteredData]
@userid int
as
begin
select D.* from Filters f
    inner join LUsersToFilters L on L.FilterId=F.Id
    inner join InformationData D on NOT (D.Title like '%'+F.KeyWord+'%') AND NOT (D.Description like '%'+F.KeyWord+'%')
where L.UserId=@userid
end