
上图显示了嵌套模型树方法.我正在搜索一个查询,当调用FRUIT或MEAT时,该查询只显示带有节点FRUIT和MEAT的1级
一世
我已经制定了一个儿童和兄弟姐妹的组合,我认为当Red被称为下面的牛肉.
INSERT
$sqlinsert = "INSERT INTO categories
(categories_id, parent_id,name, parent)
VALUES('','','$name', '$parent')";
$enterquery = mysql_query($sqlinsert) or die(mysql_error());
$customer_id = mysql_insert_id();
Run Code Online (Sandbox Code Playgroud)
我希望插入parent_id throug,关联一个新的填充被叫父对象,它将与名为"name"的现有字段相关,然后如果父字段=对现有名字字段,则从该名称字段中取出category_id,并将其作为父对象的parent_id.新的INSERTED名称.
例如,用户插入名称"blue"和父母"food",然后名称blue将采用食物的类别ID,并将其作为蓝色的parent_id ...
我认为你应该重组你的数据。让孩子持有父母的id。就现在而言,我认为您在构建查询时会遇到很多麻烦,并且当您需要添加一些节点时会遇到更多麻烦,因为您需要重新计算 left_node 和 right_node 值。
这是我认为你应该使用的表结构。
create table categories (
category_id int primary key auto_increment,
parent_id int,
name varchar(255));
alter table categories
add constraint FK_categories
foreign key (parent_id)
references categories (category_id);
Run Code Online (Sandbox Code Playgroud)
这是插入测试数据的代码。(让我们继续谈论食物:=))
insert into categories (category_id, parent_id, name)
select 1, null, 'food' union all
select 2, 1, 'fruit' union all
select 3, 2, 'red' union all
select 4, 3, 'cherry' union all
select 5, 2, 'yellow' union all
select 6, 5, 'banana' union all
select 7, 1, 'meat' union all
select 8, 7, 'beef' union all
select 9, 7, 'pork';
Run Code Online (Sandbox Code Playgroud)
水果和肉类有parent_id = 1指向食物等。
现在您需要编写的查询要简单得多。
/* Get parent */
select P.name
from categories as C
inner join categories as P
on C.parent_id = P.category_id
where C.name = 'red';
/* Get children */
select C.name
from categories as C
inner join categories as P
on C.parent_id = P.category_id
where P.name = 'red';
/* Get siblings */
select C2.name
from categories as C1
inner join categories as C2
on C1.parent_id = C2.parent_id
where C1.name = 'red';
/* Get grandparent */
select G.name
from categories C
inner join categories as P
on C.parent_id = P.category_id
inner join categories as G
on P.parent_id = G.category_id
where C.name = 'red';
Run Code Online (Sandbox Code Playgroud)
当你需要添加蓝色时,你只需要这样做。
insert into categories(parent_id, name)
values(2, 'blue');
Run Code Online (Sandbox Code Playgroud)
将蓝色的parent_id 设置为2,因为这是水果的categoriy_id。
red除 的兄弟姐妹之外的所有具有相同祖父母的节点red。
select
C2.name
from categories C
inner join categories as P
on C.parent_id = P.category_id
inner join categories as P2
on P2.parent_id = P.parent_id and
P2.category_id <> P.category_id
inner join categories as C2
on P2.category_id = C2.parent_id
where C.name = 'red';
Run Code Online (Sandbox Code Playgroud)