SQL:带可选连接的查询

时间:2010-02-25 15:52:02

标签: sql sql-server tsql full-text-search

我有一个搜索ui,其中包含3个可选搜索条件。 其中2个是where语句的简单标准,我应该能够解决这个问题:Stored Procedure with optional "WHERE" parameters

最后一个标准是使用全文搜索,我从ContainsTable加入结果。我可以用一些技巧将所有内容放在一个存储过程中吗?或者我应该进行两个查询,一个是全文搜索而另一个没有?

编辑:我应该在这里提出我的问题,对不起,这是

select Table1.* from Table1
join
(
 select [Key], SUM(Rank) as Rank from
 (
  SELECT [Key], Rank*3 as Rank FROM Table1ShortSearch(@Keywords) union all
  SELECT [Key], Rank*2 as Rank FROM Table1LongSearch(@Keywords)
 ) as RankingTbl
 group by [Key]
) as r
on Table1.Id = r.[Key]

where ( @Status_Id Is Null Or Status_Id = @Status_Id )

order by r.Rank Desc

感谢。

2 个答案:

答案 0 :(得分:3)

您可以将所有内容放在一个存储过程中并使用IF语句 - http://msdn.microsoft.com/en-us/library/ms182717.aspx

答案 1 :(得分:2)

原始答案:

你可以像这样使用EXISTS函数:

Select ..
From ..
Where ( @Status_Id Is Null Or Status_Id = @Status_Id )
 And (@Date Is Null Or [Date] = @Date )
 And (@Criteria Is Null Or Exists(
         Select 1
         From ContainsTable(TableName, Column1,...,ColumnN, @Criteria..) As SearchTable1
         Where SearchTable1.PK = OuterTable.PK
         ) )

问题修改后:

修订后的查询与原始查询完全不同。在原始查询中,您只想返回Table1中的结果,并在@Keywords不为null时另外过滤这些结果。在此查询中,您将向SELECT子句输出freetext排名。如果@Keywords被传递为null,那么排名会显示什么?

如果不需要自由文本排名,并且您只想在@Keywords上的任何一个搜索找到某些内容时返回结果,那么您可以执行以下操作:

Select ...
From Table1
Where ( @Status_Id Is Null Or Status_Id = @Status_Id )
    And ...
    And (
        @Keywords Is Null
        Or Exists   (
                    Select 1
                    From Table1ShortSearch(@Keywords) As T1
                    Where T1.Key = Table1.Key
                    )
        Or Exists   (           
                    Select 1
                    From Table1LongSearch(@Keywords) As T2
                    Where T2.Key = Table1.Key
                    )
        )

如果要显示自由文本排名,则原始查询或CTE可能是解决方案,但是如果要将@Keywords视为空,则需要使用左连接到子查询。这将使您的查询读取:

Select ...
From Table1
    Left Join   (
                 Select [Key], Sum(Rank) as Rank 
                 From   (
                        Select [Key], Rank*3 As Rank 
                        From Table1ShortSearch(@Keywords) 
                        Union All 
                        Select [Key], Rank*2 As Rank 
                        From Table1LongSearch(@Keywords)
                        ) As RankingTbl
                Group By [Key]
                ) as R
        On R.[Key] = Table1.Id
Where ( @Status_Id Is Null Or Status_Id = @Status_Id )
    And ...
    And ( @Keywords Is Null Or R.Key Is Not Null )
Order By R.Rank Desc