简体   繁体   English

SQL自联接查询? 如何获得类别子类别?

[英]Sql Self join query? How to get categories sub categories?

I've a database table, which has the following form 我有一个数据库表,其格式如下

catID | category      | parentID
1     | firstCategory | null
2     | SubCategory1  | 1
3     | SubCategory2  | 1
4     | subSub1       | 3

and so on... 等等...

There are multiple level of categories. 有多个级别的类别。 What query can be used to get the records in the following format: 可以使用哪种查询来获取以下格式的记录:

catID | category 
1     | firstCategory
2     | firstCategory/SubCategory1
3     | firstCategory/SubCategory2
4     | firstCategory/SubCategory2/subSub1

The category id will be the id of the last category. 类别ID将是最后一个类别的ID。 How to write a query to join the categories to all levels? 如何编写查询以将类别添加到各个级别? The exact number of levels for different categories is different? 不同类别的确切级别数不同?

I'm using mySQL. 我正在使用mySQL。

For a maximum depth of 6 (including root), you can use this 对于最大深度为6(包括根)的深度,您可以使用此

select l0.catID,
    concat(
      case when l5.catID is null then '' else concat(l5.category, '/') end
    , case when l4.catID is null then '' else concat(l4.category, '/') end
    , case when l3.catID is null then '' else concat(l3.category, '/') end
    , case when l2.catID is null then '' else concat(l2.category, '/') end
    , case when l1.catID is null then '' else concat(l1.category, '/') end
    , l0.category)
from catcat l0
left join catcat l1 on l0.parentID=l1.catID
left join catcat l2 on l1.parentID=l2.catID
left join catcat l3 on l2.parentID=l3.catID
left join catcat l4 on l3.parentID=l4.catID
left join catcat l5 on l4.parentID=l5.catID

Expand the pattern as required for longer max depths. 根据需要扩展图案以获得更长的最大深度。

Oracle has this functionality, and the company I work for uses it for exactly what you are describing. Oracle具有此功能,我工作的公司将其完全用于您所描述的内容。 The queries can be quite heavy at times though. 但是查询有时可能会很繁重。 A good writeup of the functions ("start with" and "connect by" keywords) is found here at this link, along with pseudo code you might try to wrap your head around...though cyberkiwi's answer is probably just fine for all practical purposes... 在此链接上可以找到很好的函数编写(“ start with”和“ connect by”关键字)以及伪代码,您可能会想把头缠起来……尽管cyberkiwi的回答可能对所有实际应用都很好目的...

http://www.adp-gmbh.ch/ora/sql/connect_by.html http://www.adp-gmbh.ch/ora/sql/connect_by.html

There is an alternative to what cyberkiwi said: Query the whole table and to the tree building in memory. Cyber​​kiwi说的还有另一种方法:查询整个表和内存中的树结构。 Imperative languages are well suited for that while SQL is not. 命令式语言非常适合于此,而SQL不适合。 The performance will be much better (because SQL has to scan the table not only once but for every level). 性能会好得多(因为SQL不仅必须扫描该表一次,而且还要扫描每个级别)。

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

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