MySQL递归搜索

时间:2012-02-06 19:02:20

标签: php mysql pdo hierarchical-data

我有5张桌子:

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 个答案:

答案 0 :(得分: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?

的回答