2012-02-06 2 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을 사용할 수 있습니까?

필요하다면 테이블 구조를 변경할 준비가되었습니다. 이것은 첫 번째 재귀 트리입니다.

답변

1

MySQL은 다른 데이터베이스처럼 재귀 쿼리를 지원하지 않습니다. parent_id를 저장하는 방법으로 단일 쿼리에서 모든 부모 범주를 찾는 방법은 없습니다.

MySQL의 트리 구조를 저장하고 쿼리하기위한 다양한 기술에 대한 개요는 내 프레젠테이션 Models for Hierarchical Data with SQL and PHP을 참조하십시오.

내 대답도 참조 What is the most efficient/elegant way to parse a flat table into a tree?