views:

54

answers:

2

I have the following query, which performs a full-text search (CONTAINSTABLE) on the Products table, and returns 1 record.

Each Product is referenced by the ShopProducts table (each ShopProduct represents a product in a shop and is has a foreign key to Products.ProductId. Each row in the ShopProducts table has a ShopId column.

My question is - how can I limit the query below to only return Products that do not have a ShopProduct for the ShopId given in the @ShopId variable?

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
A: 
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
Bill Karwin
A: 

How about

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
Steve Kass