2014-10-17 62 views
0

我試圖在MySQL中建立一個簡單的搜索功能,用戶可以通過輸入一個或多個預定義的關鍵字來過濾圖像。但是,當我添加多個關鍵字時,我無法獲得正確的輸出。來自關鍵字的MySQL結果

這裏的數據庫結構的簡化版本:

Table: images 
- id (PK) 
- title 
- link 

Table: keywords 
- id (PK) 
- keyword 

Table: image_keywords 
- image_id (FK) 
- keyword_id (FK) 

數據例如:

images: 
1.  Image 1 title http://test1.com 
2.  Image 2 title http://test2.com 
3.  Image 3 title http://test3.com 

keywords: 
1.  Photography 
2.  Landscape 
3.  Skyline 

image_keywords: 
1.  1. 
1.  2. 
2.  1. 
2.  3. 

那麼想我是能夠搜索image_keywords具有所有圖片攝影橫向作爲關鍵字並列出它們。但從理論上來說,圖像可以擁有無​​限數量的關鍵字。有什麼想法嗎?

回答

1

我認爲這可能是你想要什麼:

select i.id, i.title 
from images i 
inner join image_keywords ik on i.id = ik.image_id 
inner join keywords k on ik.keyword_id = k.id 
where k.keyword in ('Photography', 'Landscape') 
group by i.id, i.title 
having count(distinct k.id) = 2 

Sample SQL Fiddle

+1

真棒,正是我一直在尋找。非常感謝您的幫助! – 2014-10-19 20:24:14