2012-02-06 130 views
1

我有5個表:MySQL的遞歸搜索

library_item 
============ 
id 
title 
description 
index_text 

library_item_rel_category 
========================= 
item_id 
category_id 

library_category 
================ 
id 
parent_id 
name 

library_item_rel_tag 
==================== 
item_id 
tag_id 

library_tag 
=========== 
id 
name 

而且目前我有這個MySQL請求(使用PHP PDO):

SELECT 
    i.*, 
    ((
     ((MATCH (i.title) AGAINST (:terms)) * 5) + 
     ((MATCH (i.description) AGAINST (:terms)) * 4) + 
     ((MATCH (i.index_text) AGAINST (:terms)) * 3) + 
     (MATCH (i.title, i.description, i.index_text) AGAINST (:terms)) 
    ) + IFNULL(c.score, 0) + IFNULL(t.score, 0)) as score 
FROM 
    library_item AS i 
LEFT JOIN 
    (
     SELECT 
      rel_c.item_id, 
      ((MATCH(c.name) AGAINST (:terms)) * 5) AS score 
     FROM 
      library_item_rel_category rel_c 
     INNER JOIN 
      library_category c ON rel_c.category_id = c.id 
     WHERE 
      MATCH(c.name) AGAINST (:terms) 
     ORDER BY 
      score DESC 
    ) AS c ON c.item_id = i.id 
LEFT JOIN 
    (
     SELECT 
      rel_t.item_id, 
      ((MATCH(t.name) AGAINST (:terms)) * 5) AS score 
     FROM 
      library_item_rel_tag rel_t 
     INNER JOIN 
      library_tag t ON rel_t.tag_id = t.id 
     WHERE 
      MATCH(t.name) AGAINST (:terms) 
     ORDER BY 
      score DESC 
     LIMIT 1 
    ) AS t ON t.item_id = i.id 
WHERE 
    i.is_archive = 0 AND 
    ((
     ((MATCH (i.title) AGAINST (:terms)) * 5) + 
     ((MATCH (i.description) AGAINST (:terms)) * 4) + 
     ((MATCH (i.index_text) AGAINST (:terms)) * 3) + 
     (MATCH (i.title, i.description, i.index_text) AGAINST (:terms)) 
    ) + IFNULL(c.score, 0) + IFNULL(t.score, 0)) > 5 
GROUP BY 
    i.id 
ORDER BY 
    score DESC 

我想補充匹配父類的能力直到擊中根。在單個查詢中可以使用MySQL嗎?

如果需要,我準備好更改表結構,這是我的第一個遞歸樹。

回答