2011-10-09 105 views
0

我有兩個表(_video,_video_tag)像這樣。mysql搜索查詢一對多表

我如何構建一個最佳搜索查詢?

我想在這個領域(標題,描述,標籤)

mysql> describe _video; 
+-------------+---------------+------+-----+-------------------+----------------+ 
| Field  | Type   | Null | Key | Default   | Extra   | 
+-------------+---------------+------+-----+-------------------+----------------+ 
| id   | int(11)  | NO | PRI | NULL    | auto_increment | 
| user_id  | int(11)  | NO | MUL | NULL    |    | 
| image  | varchar(255) | NO |  | NULL    |    | 
| source  | varchar(255) | YES |  | NULL    |    | 
| duration | int(11)  | NO |  | NULL    |    | 
| title  | varchar(255) | NO |  | NULL    |    | 
| slug  | varchar(255) | NO |  | NULL    |    | 
| description | text   | NO |  | NULL    |    | 
| order  | int(11)  | NO |  | 0     |    | 
| hit   | int(11)  | NO |  | 1     |    | 
| status  | enum('0','1') | NO |  | 1     |    | 
| date_add | timestamp  | NO |  | CURRENT_TIMESTAMP |    | 
+-------------+---------------+------+-----+-------------------+----------------+ 

mysql> select * from _video_tag limit 5; 
+----------+------------------------------------+ 
| video_id | tag        | 
+----------+------------------------------------+ 
| 17748 | cevahir almanca dersi    | 
| 17748 | genis aile       | 
| 17748 | ulvi        | 
| 17748 | cevahir       | 
| 17749 | oyle bir geçer zamanki 
+----------+------------------------------------+ 

回答

0

這取決於你想要得到什麼搜索,提供哪些信息。不過,我假設您想在_video_tag中獲得給定信息from _video的特定標籤。然後,你做

select v.* from _video_tag as vt left join _video as v on v.id = vt.video_id where vt.tag = 'Specify tag';

+0

我也搜索標題和說明。您的查詢只在標籤中搜索 – alioygur

0

如果你的表是MyISAM的最好的可擴展的方式是讓在標題和描述一個FULLTEXT指數_視頻表:

CREATE FULLTEXT INDEX title_desc ON _video(title, description) 

和一個在_video_tag表標籤欄:

CREATE FULLTEXT INDEX tag ON _video_tag(tag) 

,然後查詢這樣的:

(SELECT *, 
    MATCH(title, description) AGAINT('some query string') AS relevance 
    FROM _video 
    WHERE MATCH(title, description) AGAINT('some query string')) 
UNION 
(SELECT v.* 
    MATCH(vt.tag) AGAINST('some query string') AS relevance 
    FROM _video_tag AS vt 
    INNER JOIN _video AS v ON(v.id = vt.video_id) 
    WHERE MATCH(vt.tag) AGAINST('some query string')) 
ORDER BY relevance DESC 
+0

noboddy感謝您的回答,但此查詢包含任何語法錯誤「您的SQL語法中有錯誤;請查看與您的MySQL服務器版本相對應的手冊, )ORDER BY相關性DESC'在第10行「 – alioygur

+0

@alio對不起,更正。 – nobody

+0

謝謝。留下一個問題。這個查詢結果包含重複行:(如何解決這個問題 – alioygur