我在OracleDB 12c中有以下表格
分类表:
+-------------+-----------+---------------------+
| CATEGORY_ID | PARENT_ID | DESCRIPTION |
+-------------+-----------+---------------------+
| 1 | (null) | Category 1 |
| 2 | (null) | Category 2 |
| 3 | (null) | Category 3 |
| 4 | (null) | Category 4 |
| 5 | 1 | Subcategory level 1 |
| 6 | 5 | Subcategory level 2 |
| 7 | 6 | Subcategory level 3 |
| 8 | 2 | Subcategory level 1 |
| 9 | 3 | Subcategory level 1 |
| 10 | 4 | Subcategory level 1 |
+-------------+-----------+---------------------+
用户表:
+---------+-------+
| USER_ID | NAME |
+---------+-------+
| 1 | Ben |
| 2 | Frank |
+---------+-------+
订单表:
+----------+-------------+---------+
| ORDER_ID | CATEGORY_ID | USER_ID |
+----------+-------------+---------+
| 1 | 1 | 1 |
| 2 | 7 | 2 |
+----------+-------------+---------+
我希望获得order_id
的每个类别和子类别的信息。
E.g:
给定order_id = 2
,找到每个类别和子类别:
+-------------+-----------+---------------------+
| CATEGORY_ID | PARENT_ID | DESCRIPTION |
+-------------+-----------+---------------------+
| 1 | (null) | Category 1 |
| 5 | 1 | Subcategory level 1 |
| 6 | 5 | Subcategory level 2 |
| 7 | 6 | Subcategory level 3 |
+-------------+-----------+---------------------+
我尝试使用CONNECT BY
,您可以在以下SQLFiddle中看到,但它给了我很多“无用的”行。
答案 0 :(得分:1)
这样的东西?
SQL> select c.category_id, c.parent_id, c.description
2 from categories c
3 start with c.category_id = (select o.category_id from orders o
4 where o.order_id = 2)
5 connect by c.category_id = prior c.parent_id
6 order by c.category_id;
CATEGORY_ID PARENT_ID DESCRIPTION
----------- ---------- -------------------------
1 Category 1
5 1 Subcategory level 1
6 5 Subcategory level 2
7 6 Subcategory level 3
SQL>