简体   繁体   English

MYSQL返回父和子

[英]MYSQL return parent & child

Ok so I have a table called categories that looks like this: 好的,我有一个名为categories的表,如下所示:

id       name      parent_id
1        camera    null
2        computer  null
3        digital   1
4        gps       null
5        laptop    2

I want to be able to return computer -> laptop or camera -> digital when I query id = 3 or 5. 我希望能够在查询id = 3或5时返回计算机 - >笔记本电脑或相机 - >数字。

Any ideas? 有任何想法吗?

Try Nestedsets for those Structurs. 为这些Structurs尝试Nestedsets It has a very good performance for selecting, but a bad performance for writing. 它有选择非常不错的表现,但是对于编写糟糕的表现。 So if you have much more Selects, as Insert or Updates (Structure Updates) on your Table its a good choice to use nested sets. 因此,如果你有更多的选择,作为表上的插入或更新(结构更新),它是使用嵌套集的一个很好的选择。

Breadcrumps with Nested Sets to get Category 1 -> SubCategory -> SubCategory 带有嵌套集的Breadcrumps获得类别1 - > SubCategory - > SubCategory

if it's fixed column count of results set 如果它是结果集的固定列数

select p.name, c.name
mytable c, mytable p
where c.parent_id = p.id
and c.id in (3,5)

What you are trying to use is an anti-pattern. 你想要使用的是反模式。 If you continue using it you may encoutner some problems when you will want to select entire trees of subcategories. 如果您继续使用它,当您想要选择整个子类别树时,可能会遇到一些问题。 Look at take's answer for proper pattern. 看看正确模式的答案。

select t2.name + "->" + t1.name 
from categories t1
inner join t2 on t1.id = t2.parent_id
where t1.id in (3, 5)

If you only have one level of parent - child references: 如果您只有一个级别的父子引用:

SELECT IF(p.name IS NOT NULL, p.name + " -> " + a.name, a.name) AS name
FROM categories a
LEFT JOIN categories p ON a.parent_id = p.id

Use a self left join : 使用自我左连接:

select a.name, b.name as parent_name from categories a left join categories b on a.parent_id = b.id where a.id in (3,5);

Above query is valid for getting a one level of parent. 以上查询对于获得一级父级是有效的。 If you want to traverse through the whole lineage please refer the following link. 如果您想遍历整个世系,请参阅以下链接。 They have listed down few standard ways of traversing tree : 他们列出了几种遍历树的标准方法:

http://jan.kneschke.de/projects/mysql/sp/ http://jan.kneschke.de/projects/mysql/sp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM