这是用于存储类别/子类别站点导航的表:
$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,返回的行是 - carrot,tomato,potato,celery,rutabaga。 如果给出的 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 给定部分,我可以放弃返回叶节点。现在我只需要一个将返回所有叶节点的查询,给定一个类别/子类别节点。再次感谢
最佳答案
所以我使用的最终查询如下所示:
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。 它的工作。希望它将继续这样做,因为我在这里有点猜测。
关于mysql - 邻接模型,给定一个 id 返回叶节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10512794/