2015-03-31 47 views
1

我有三個表中的SQL服務器 -獨特的結果搜索算法,多個標籤

Photos table: 

---------------------- 
| PhotoId | PhotoName| 
---------------------- 
|   |   | 
---------------------- 

Tags table: 

---------------------- 
| TagId | TagName| 
---------------------- 
|   |   | 
---------------------- 

Junction table: 

---------------------- 
| PhotoId | TagId | 
---------------------- 
|   |   | 
---------------------- 

一張照片可以有多個標籤,並且標籤可以屬於多個照片。

現在,例如Eagle有標籤Bird, Animal, Wild。我想用標籤搜索Domestic, Bird, Animal。我正在使用sql語句where TagName='Domestic' OR TagName='Bird' OR TagName='Animal'。問題是,它會在Eagle出現兩次時產生查詢結果。

但我想只有一次鷹。任何想法?

回答

2
SELECT p.* 
FROM photos p 
WHERE EXISTS (SELECT 'a' 
       FROM junction j 
       JOIN tags t ON t.TagId = j.TagId 
       WHERE p.PhotoId = j.PhotoId 
       AND t.TagName IN ('Domestic', 'Bird', 'Animal') 
      ) 
+0

有了正確的指標,這可能是最快的解決方案。 – 2015-03-31 12:11:57

1

與DISTINCT每張照片只能出現在結果設置一次

select * from Photos 
where PhotoId in 
( select DISTINCT PhotoId 
    from Junction 
    where TagId in 
    (select TagId from Tags where TagName='Domestic' OR TagName='Bird' OR TagName='Animal') 
) 
2
select distinct p.* 
from photos p 
inner join Junction j on j.PhotoId = p.PhotoId 
inner join tags t on j.TagId = t.TagId 
where t.TagName in ('Domestic', 'Bird','Animal') 
2

我能想到的,你僅僅只需要指定照片的名字最快的解決辦法,然後做一個獨特的,那麼動物的每個名稱將根據標籤顯示一次。

SELECT DISTINCT PhotoName 
FROM Tags T 
JOIN Junction J ON J.TagId = T.TagId 
JOIN Photos P ON P.PhotoId = J.PhotoId 
WHERE TagName=('Domestic' OR TagName='Bird') OR TagName='Animal'