【问题标题】:Filtering Records From Database从数据库中过滤记录
【发布时间】:2013-12-13 05:31:11
【问题描述】:

我在数据库中有 4 个表

  1. Users 与列 Id, Email, Password, Active
  2. InformationData 与列 Id, Title, Description, Link
  3. Filters 与列 Id, Keyword, Active
  4. LUserToFilter 与列 UserId, FilterId

现在我想要从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

请给点建议..

【问题讨论】:

  • 旁注:您应该为您的存储过程使用sp_ 前缀。微软有reserved that prefix for its own use (see Naming Stored Procedures),你确实会在未来某个时候冒着名称冲突的风险。 It's also bad for your stored procedure performance。最好只是简单地避免 sp_ 并使用其他东西作为前缀 - 或者根本不使用前缀!
  • 好吧抱歉使用 sp_ 和英文写作,但以这种方式写英文是我的习惯,我会努力改掉它
  • 我仍然不完全清楚你想要过滤掉什么(例如不显示),以及你想要显示哪些行。我是否理解正确:您想在标题或描述列中显示来自InformationData 的那些不包含来自Filters 的任何字词的行?
  • 我需要的正是你所理解的......

标签: sql database sql-server-2008 join


【解决方案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)

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • 对我不起作用,但感谢您的回答我解决了我的问题并发布了答案。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)
    猜你喜欢
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多