2014-06-27 127 views
0

我目前正在爲音樂網站編寫基本搜索系統,系統使用標籤('Instrumental Duo','Instrumental Trio','latin',..ect)進行搜索。我試圖找出如何使用標籤搜索MySQL數據庫來限制結果。基於MySQL標籤的系統

這些表的目的是相關的;

| Items |   | Tags  | 
|----------|   |----------| 
| PK_Items | One - Many | FK_Items | 
| Title |   | PK_Tags | 
| Writer |   | Tag_txt | 

表中的每個項目項目將在表中的多個項目標籤

總之我希望能夠給數據庫的標籤集合,並將它歸還所有匹配


示例數據

的項代

該表已被使用

CREATE TABLE Items 
(
    PK_Items int NOT NULL AUTO_INCREMENT, 
    Title TEXT, 
    Writer varchar(30), 
    PRIMARY KEY(PK_Items) 
); 
CREATE TABLE Tags 
(
    PK_Tags int NOT NULL, 
    FK_Items int NOT NULL, 
    Tag_Txt varchar(100), 
    PRIMARY KEY(PK_Type), 
    FOREIGN KEY(FK_Items) REFERENCES Items(PK_Items) 
); 

樣本數據

+----------+-------------+------------------+ 
| <b>PK_Items</b> | <b>Title</b>  | <b>Writer</b>   | 
+----------+-------------+------------------+ 
|  1 | Song1  | Joe Blogs  | 
+----------+-------------+------------------+ 
|  2 | Song2  | Joe Blogs  | 
+----------+-------------+------------------+ 
|  3 | Song3  | Jane Smith  | 
+----------+-------------+------------------+ 

+----------+-------------+------------------+ 
| <b>PK_Tags</b> | <b>FK_Items</b> | <b>Tag_Txt</b>   | 
+----------+-------------+------------------+ 
|  1 |   1 | Slow    | 
+----------+-------------+------------------+ 
|  2 |   1 | Jazz    | 
+----------+-------------+------------------+ 
|  3 |   2 | Fast    | 
+----------+-------------+------------------+ 
|  4 |   2 | Rock    | 
+----------+-------------+------------------+ 
|  5 |   3 | Slow    | 
+----------+-------------+------------------+ 
|  6 |   3 | Rock    | 
+----------+-------------+------------------+ 

創建如果我想搜索「慢」,我應該有與慢速標籤例如顯示所有項目

+----------+-------------+------------------+ 
| <b>PK_Items</b> | <b>Title</b>  | <b>Writer</b>   | 
+----------+-------------+------------------+ 
|  1 | Song1  | Joe Blogs  | 
+----------+-------------+------------------+ 
|  3 | Song3  | Jane Smith  | 
+----------+-------------+------------------+ 

或者,如果我搜索 「慢」 和 「搖滾」,我會得到

+----------+-------------+------------------+ 
| <b>PK_Items</b> | <b>Title</b>  | <b>Writer</b>   | 
+----------+-------------+------------------+ 
|  3 | Song3  | Jane Smith  | 
+----------+-------------+------------------+ 

我已經試過

SELECT * 
FROM Items a 
JOIN Type t ON t.FK_Items = a.PK_Items 
WHERE t.Tag_txt = 'Slow'; 

其中給出(基本上)是什麼它應該給,但是當使用「慢」和「搖滾」我得到一張空的桌。

SELECT * 
FROM Items a 
JOIN Type t ON t.FK_Items = a.PK_Items 
WHERE t.Tag_txt = 'Slow' AND t.Tag_txt = 'Rock'; 

請幫助

回答

1

您可以使用having條款做到這一點。這裏有一種方法:

SELECT i.* 
FROM Items i JOIN 
    Type t 
    ON t.FK_Items = i.PK_Items 
WHERE t.Tag_txt IN *'Slow', 'Rock') 
GROUP BY i.PK_Items 
HAVING COUNT(DISTINCT t.tag_txt) = 2;