需要有关分层Mysql查询的帮助

时间:2011-04-16 21:09:18

标签: mysql hierarchical-data

我正在试图查询一个具有分层类别数据(用于cms)的表,这也与我的帖子数据和我的post2cat表的多对多类型关系有关。具体来说,我的问题是如何获得属于特定类别ID的任何子类别(不限于直接后代但可以是n级深度)的所有帖子?这是我的表格:

'类别'表:

+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id        | int(11)     | NO   | PRI | NULL    | auto_increment |
| name      | varchar(45) | YES  |     | NULL    |                |
| parent_id | int(11)     | YES  | MUL | 0       |                |
+-----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

'post2cat'表:

+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| post_id | int(11) | NO   | MUL | NULL    |       |
| cat_id  | int(11) | NO   | MUL | NULL    |       |
+---------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

'posts'表:

+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| title         | varchar(256) | NO   |     | NULL    |                |
| content       | text         | NO   |     | NULL    |                |
| end_date      | datetime     | NO   |     | NULL    |                |
| format_id     | int(11)      | NO   |     | NULL    |                |
| featured      | int(1)       | NO   |     | NULL    |                |
| status        | int(3)       | NO   |     | NULL    |                |
| publish_date  | datetime     | NO   |     | NULL    |                |
| date_created  | datetime     | NO   |     | NULL    |                |
| date_modified | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+

post_id名称说明

post2cat

3 个答案:

答案 0 :(得分:4)

使用MySQL中的SQL,将树提取到任意深度 n 是一项挑战(参见:Managing Hierarchical Data in MySQLHierarchical Queries in MySQL)。

如果您正在处理一个小数据集,那么最有意义的是从数据库中选择所有类别,然后使用脚本语言构建树。然后可以遍历树以查找父节点和父节点的子节点,然后可以使用它来使用连接查询数据库中的帖子。

答案 1 :(得分:1)

也许有更好的方法,但这是一个想法:

CREATE VIEW subcategories AS
( SELECT 0        AS level
       , cat_0.id AS cat_id
       , cat_0.id AS subcat_id
  FROM categories cat_0

  UNION ALL

  SELECT 1        AS level
       , cat_0.id AS cat_id
       , cat_1.id AS subcat_id
  FROM categories cat_0
    JOIN categories cat_1
      ON cat_0.id = cat_1.parent_id

  UNION ALL

  SELECT 2        AS level
       , cat_0.id AS cat_id
       , cat_2.id AS subcat_id
  FROM categories cat_0
    JOIN categories cat_1
      ON cat_0.id = cat_1.parent_id
    JOIN categories cat_2
      ON cat_1.id = cat_2.parent_id

  UNION ALL

  SELECT 3        AS level
       , cat_0.id AS cat_id
       , cat_3.id AS subcat_id
  FROM categories cat_0
    JOIN categories cat_1
      ON cat_0.id = cat_1.parent_id
    JOIN categories cat_2
      ON cat_1.id = cat_2.parent_id
    JOIN categories cat_3
      ON cat_2.id = cat_3.parent_id
) ;

然后,使用上面的内容:

SELECT sub.subcat_id
     , sub.level
     , p.post_id
     , p.title
FROM subcategories sub
  JOIN post2cat p2c
    ON sub.subcat_id = p2c.cat_id
  JOIN posts p
    ON p2c.post_id = p.id
WHERE sub.cat_id = CAT_ID        <--- the category id you want to search for

答案 2 :(得分:0)

以下存储过程应该提供一个良好的起点或提供一些灵感。

希望有所帮助:)

示例调用

您可以按如下方式从php调用存储过程:

$result = $conn->query(sprintf("call category_hier(%d)", 1));

或者从mysql命令行:

mysql> call category_hier(1);
+--------+---------------+---------------+----------------------+-------+
| cat_id | category_name | parent_cat_id | parent_category_name | depth |
+--------+---------------+---------------+----------------------+-------+
|      1 | Location      |          NULL | NULL                 |     0 |
|      3 | USA           |             1 | Location             |     1 |
|      4 | Illinois      |             3 | USA                  |     2 |
|      5 | Chicago       |             3 | USA                  |     2 |
+--------+---------------+---------------+----------------------+-------+
4 rows in set (0.00 sec)

完整脚本

drop table if exists categories;
create table categories
(
cat_id smallint unsigned not null auto_increment primary key,
name varchar(255) not null,
parent_cat_id smallint unsigned null,
key (parent_cat_id)
)
engine = innodb;

insert into categories (name, parent_cat_id) values
('Location',null), 
('Color',null), 
   ('USA',1), 
      ('Illinois',3), 
      ('Chicago',3), 
   ('Black',2), 
   ('Red',2);


drop procedure if exists category_hier;
delimiter #

create procedure category_hier
(
in p_cat_id smallint unsigned
)
begin

declare v_done tinyint unsigned default 0;
declare v_depth smallint unsigned default 0;

create temporary table hier(
 parent_cat_id smallint unsigned, 
 cat_id smallint unsigned, 
 depth smallint unsigned default 0
)engine = memory;

insert into hier select parent_cat_id, cat_id, v_depth from categories where cat_id = p_cat_id;
create temporary table tmp engine=memory select * from hier;

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

while not v_done do

    if exists( select 1 from categories c
        inner join tmp on c.parent_cat_id = tmp.cat_id and tmp.depth = v_depth) then

        insert into hier select c.parent_cat_id, c.cat_id, v_depth + 1 from categories c
            inner join tmp on c.parent_cat_id = tmp.cat_id and tmp.depth = v_depth;

        set v_depth = v_depth + 1;          

        truncate table tmp;
        insert into tmp select * from hier where depth = v_depth;

    else
        set v_done = 1;
    end if;

end while;

select 
 c.cat_id,
 c.name as category_name,
 p.cat_id as parent_cat_id,
 p.name as parent_category_name,
 hier.depth
from 
 hier
inner join categories c on hier.cat_id = c.cat_id
left outer join categories p on hier.parent_cat_id = p.cat_id
order by
 hier.depth;

drop temporary table if exists hier;
drop temporary table if exists tmp;

end #

delimiter ;

call category_hier(1);

call category_hier(2);