2014-01-30 34 views
0

我有一個困難的mysql問題。我有一個匹配的關鍵字數據庫的情況下,簡化:困難的MySQL問題(關係和多行)

TABLE cases (id) 
TABLE keywords (id) 
TABLE cases_keywords (case, keyword) 

所以我可以有一個情況下使用關鍵字Y和Z,我可以有關鍵字X的情況下B和Y.這給了我四排cases_keywords:

(A, Y) 
(A, Z) 
(B, X) 
(B, Y) 

問題:

我有我的網站上,用戶在關鍵詞進行搜索鍵入搜索。我希望結果在找到所有關鍵字時顯示匹配。所以當用戶輸入Y和Z作爲關鍵字時,只會出現情況A(因爲情況B沒有關鍵字Z)。但是,當用戶只給Y作爲關鍵字時,站點顯示A和B(因爲它們都得到關鍵字Y)。

所以我知道通過PHP動態的queryis,最大的問題是,以匹配多個關鍵字...比方說,我想匹配2個關鍵字:Y與結果Z:A.情況

怎麼辦我把它編入查詢中?我怎麼能匹配多行?

SELECT C.id FROM cases C JOIN cases_keywords CK ON CK.case = C.id WHERE CK.keyword = Y AND CK.keyword = Z 

上面沒有工作,所以我試圖用WHERE C.case IN(),但我被困有太多的東西......

有人請幫助我

回答

1

2建議在這裏。

第一個必須動態構建,並不會那麼高效,但它很容易理解。

SELECT C.id 
FROM cases C 
JOIN cases_keywords CK1 ON CK1.case = C.id AND CK1.keyword = Y 
JOIN cases_keywords CK2 ON CK2.case = C.id AND CK2.keyword = Z 

更高效,可以無動態構建: -

SELECT C.id, COUNT(CK.keyword) AS KeywordCount 
FROM cases C 
JOIN cases_keywords CK ON CK.case = C.id 
WHERE CK.keyword IN ('Y', 'Z') 
GROUP BY C.id 
HAVING KeywordCount = 2 
0

如果你可以使用MyISAM存儲引擎(或者InnoDB的在MySQL 5.6),你可以做全文索引以下(然後可以讓你有關鍵字實際上短語):

CREATE TABLE cases (id INT AUTO_INCREMENT PRIMARY KEY, 
        name VARCHAR(10) NOT NULL) Engine = MyISAM; 

CREATE TABLE keywords (id INT AUTO_INCREMENT PRIMARY KEY, 
         word VARCHAR(10) NOT NULL) Engine = MyISAM; 

ALTER TABLE keywords ADD FULLTEXT INDEX (word); 

CREATE TABLE cases_keywords (`case` INT, 
          keyword INT, 
          PRIMARY KEY (`case`,keyword)) Engine = MyISAM; 

INSERT INTO cases VALUES (1,'Alpha'),(2,'Beta'); 
INSERT INTO keywords VALUES (1,'Xylophone'),(2,'Yaks'),(3,'Zebra'); 

INSERT INTO cases_keywords VALUES (1,2),(1,3),(2,1),(2,2); 

SELECT `cases`.name, COUNT(keywords.id) AS matches 
FROM `cases` 
JOIN cases_keywords 
    ON cases_keywords.case = `cases`.id 
JOIN keywords 
    ON keywords.id = cases_keywords.keyword 
WHERE MATCH(word) AGAINST ('(Yaks Zebra) ("Yaks Zebra") (+Yaks* +Zebra*)' IN BOOLEAN MODE) 
GROUP BY `cases`.id 
ORDER BY matches DESC 

工作SQLFiddle:http://sqlfiddle.com/#!2/49c19/2

很明顯,你可以調整的全文檢索工作你想怎麼的,但我們使用以下布爾模式搜索做以下(這符合我們的要求):

(Yaks Zebra) -> matches any occurence in the `word` column of Yak or Zebra 
("Yaks Zebra") -> matches the whole phrase "Yaks Zebra" in the `word` column 
(+Yaks* +Zebra*) -> requires both Yaks and Zebra to be in the `word` column, but 
        also allows extra characters after each of those words...