选择项目,然后选择父项的名称

时间:2009-02-20 23:31:39

标签: mysql

晨间:

表格结构:

id | name | parent_id

我想运行ID的查询,但也返回该项的parent_id以及该ID的名称。

更好地解释

SELECT id, name FROM sections

...然后对于每个ID,使用“parent_id”列返回其父级的ID和名称。

我想把它变成一个数组:

[0]
    [id]
    [name]
    [parent_id]
    [parent_name]

5 个答案:

答案 0 :(得分:5)

这应该有效:

SELECT s.id, s.name, s.parent_id, p.name as parent_name
FROM sections s LEFT JOIN sections p ON s.parent_id = p.id

基本上你只想加入自己的表格,并将名称字段作为父名称。

答案 1 :(得分:1)

SELECT a.id, a.name, b.id as parent_id, b.name as parent_name
FROM sections a
INNER JOIN sections b on a.parent_id = b.id

(如果有没有父节点的节点,也可以进行外连接)

答案 2 :(得分:1)

只需将表格加入自身

类似的东西:

SELECT child.id,child.name,child.parent_id,parent.name AS parentname FROM tablename子LEFT JOIN tablename parent ON child.parent_id = parent.id

答案 3 :(得分:1)

进行连接比简单地进行子选择更有效吗?

select id as childID , name as childName, parent_id as pid, (select id from sections where id = pid) as parentID, (select name from sections where id = pid) as parentName from sections;

更大的问题是这不是递归的...我很好奇如何让这种情况无限制地增加为多代人的关系。

答案 4 :(得分:0)

你可以有很多解决方案,比如::

1>

Select id as id, name as id_name, (Select id from sections where id=parent_id) as parent_id, (Select name from sections where id=parent_id) as parent_name 
from sections where .....

2>

Select child.id, child.name, parent.id, parent.name 
 from sections child
 inner join sections parent on (parent.id=child.parent_id)
 where .....

你可以实现任何一个,但我更喜欢第二个......