【问题标题】:adjacency model , given an id return the leaf nodes邻接模型,给定一个 id 返回叶节点
【发布时间】:2012-05-09 08:54:12
【问题描述】:

这是用于存储类别/子类别网站导航的表格:

   $query = "CREATE TABLE categories (
    id int(11) NOT NULL auto_increment,
    name varchar(100) NOT NULL,
    parentid int(11) NOT NULL,
     PRIMARY KEY  (id)
)"  ;

说这些是表格内的条目

id  name    parentid
1   animal  NULL
2   vegetable NULL
3   mineral NULL
4   doggie  1
5   kittie  1
6   horsie  1
7   gerbil  1
8   birdie  1
9   carrot  2
10  tomato  2
11  potato  2
12  celery  2
13  rutabaga    2
14  quartz  3

我想要的是这样一个 sql 查询,对于给定的 id ,返回所有叶节点,如果给出叶节点的 id,则返回叶节点本身。

因此,如果设置了 id 2,则返回的行是 - 胡萝卜、番茄、马铃薯、芹菜、大头菜。 如果给定的id是9,则返回的行是-9本身

可能吗?

我的子类别不会超过 3 个级别。

我尝试了on this page 给出的代码,但如果给出了叶节点 id,它没有给出叶节点。

谢谢

我尝试了一些查询..

    SELECT distinct t1.name FROM
categories AS t1 LEFT JOIN categories as t2
ON t1.id = t2.parent
 LEFT JOIN categories as t3
ON t2.id = t3.parent
WHERE  t1.parent = ? OR t1.id = ?

但我根本无法理解连接。

编辑:如果叶节点 id 给定 part ,我可以放弃返回叶节点。现在我只需要一个返回所有叶子节点的查询,给定一个类别/子类别节点。再次感谢

【问题讨论】:

  • 你现在尝试的查询是什么
  • 如果您摆脱邻接表并使用嵌套集或闭包表,您的生活会轻松很多...请参阅this answer
  • 我同意 eggyval:因为 MySQL(仍然)不支持递归查询,所以使用邻接模型并不适合 MySQL
  • 我认为您需要拆分表,否则请尝试使用我的代码进行查询

标签: mysql


【解决方案1】:

所以我使用的最终查询如下所示:

SELECT distinct t2.id , t2.name FROM
    categories AS t1 LEFT JOIN categories as t2
    ON t1.id = t2.parent
     LEFT JOIN categories as t3
    ON t2.id = t3.parent
    WHERE  t1.parent = $id OR t1.id = $id and t2.visible = 1

如果返回一个空结果集,这意味着提供了一个结束节点,我只需返回提供的 $id。 它的工作。希望它会继续这样做,因为我在这里有点猜测。

【讨论】:

    【解决方案2】:

    试试这个代码:

    select * from `categories` where id=something and parentid is not null 
    union all
    select * from `categories` where parentid=something;
    

    并告诉我它是否有效(用所需的值替换一些东西)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2015-08-14
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多