SQL Server 2008 - 限制FK的查询

时间:2009-09-20 17:15:19

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

我有以下查询,它在 Products 表上执行全文搜索(CONTAINSTABLE),并返回1条记录。

ShopProducts 表引用了每个产品(每个 ShopProduct 代表商店中的产品,并且具有的外键> Products.ProductId ShopProducts 表中的每一行都有一个 ShopId 列。

我的问题是 - 我如何限制下面的查询只返回产品 具有给出的ShopId的 ShopProduct @ShopId变量?

DECLARE @ShopId uniqueidentifier
DECLARE @FullTextQuery nvarchar(1000)

SET @ShopId = 'a7e7d519-27f0-4d95-a1dd-87d992a0478c'

SET @FullTextQuery = 'ISABOUT("*Palmolive*","*Naturals*","*Shower*","*Milk*","*Nourishing*","*With*","*Honey*")'


SELECT TOP 1
       ftt.RANK,
       p.ProductId, 
       p.SearchableDescription
 FROM Products p
 JOIN CONTAINSTABLE(Products, 
                    SearchableDescription, 
                    @FullTextQuery) AS ftt ON ftt.key = p.ProductId 
ORDER BY ftt.RANK DESC

2 个答案:

答案 0 :(得分:0)

SELECT TOP 1
 ftt.RANK, p.ProductId, p.SearchableDescription
FROM Products p
INNER JOIN CONTAINSTABLE(Products, SearchableDescription, @FullTextQuery) AS ftt
 ON ftt.[KEY]=p.ProductId
LEFT OUTER JOIN ShopProduct s
 ON (p.ProductId = s.ProductId AND s.ShopId = @ShopId)
WHERE s.ProductId IS NULL
ORDER BY ftt.RANK DESC

答案 1 :(得分:0)

怎么样

WITH ProductsExcept(ProductId,SearchableDescription) as (
  SELECT ProductId, SearchableDescription
  FROM Products p
  WHERE NOT EXISTS (
    SELECT * FROM ShopProducts
    WHERE ShopProducts = ProductID
    AND ShopID <> @ShopId 
  )
)
  SELECT  
    ftt.RANK,
    p.ProductId, 
    p.SearchableDescription
 FROM ProductsExcept p
 JOIN CONTAINSTABLE(Products, 
                    SearchableDescription, 
                    @FullTextQuery) AS ftt ON ftt.key = p.ProductId 
ORDER BY ftt.RANK DESC