【问题标题】:Need Help with Hierarchical Mysql Query需要有关分层 Mysql 查询的帮助
【发布时间】:2011-04-16 21:09:18
【问题描述】:

我正试图集中精力查询一个具有分层类别数据(用于 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)

“帖子”表:

+---------------+--------------+------+-----+---------+----------------+
| 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

【问题讨论】:

  • categories表是一个邻接表模型。使用 MySQL 会话变量来遍历树。我关于 SQL 中分层数据的问题涵盖了更多关于这个一般问题的内容:stackoverflow.com/questions/4048151/…

标签: mysql hierarchical-data


【解决方案1】:

在 MySQL 中仅使用 SQL 将树提取到任意深度是一个挑战n(请参阅:Managing Hierarchical Data in MySQLHierarchical Queries in MySQL)。

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

【讨论】:

  • +1 表示您提供的第一个链接。但是,您的评论与链接的内容不一致。似乎您不需要使用脚本语言,因为您使用的是嵌套集模型。
  • 在 MySQL 中,为了从邻接表模型中检索树,您需要知道深度。第二个链接是尝试解决这个问题。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    以下存储过程应该提供一个很好的起点或提供一些启发。

    希望对你有帮助:)

    调用示例

    你可以从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);
    

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2011-06-30
      • 2011-04-23
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多