获取顶级类别中的所有子类别

时间:2011-08-24 04:46:00

标签: postgresql

获取所有使用postgresql的子类别所需的sql是什么

My Table : Category_map

-------------+--------------+------------
category_id  category_name  parent_id
------------+--------------+----------
1 Agriculture 0 
2 Appearl & Fashion 0 
3 Chemicalas 0 
4 Plastic & Plastic Products 0 
5 Automobile 0 
14 Coconut Shell Products 1 
15 Nuts & Kernels 1 
16 Plant & Animal Oil 1 
17 Potpourri 1 
18 Raw Cotton & Cotton Waste 1 
19 Rice 1 
20 Tea 1 
21 Seeds 1 
22 Vegetable 1 
23 White Rice 19 
24 Green Rice 19 
25 Basmati Rice 19 
26 Boiled Rice 19 
27 Fresh Preserved Vegetables 22 
28 Frozen & Dried Vegetables 22 
29 Others 22 
30 Activated Carbon 3 

我需要sql查询来获取parentid = 0的顶级类别中的所有子类别

请帮帮我

感谢

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

SELECT t1.* FROM category_map t1
  JOIN (SELECT * FROM category_map WHERE parent_id = 0) t2
    ON t1.parent_id = t2.category_id;

+-------------+---------------------------+-----------+
| category_id | category_name             | parent_id |
+-------------+---------------------------+-----------+
|          14 | Coconut Shell Products    |         1 |
|          15 | Nuts & Kernels            |         1 |
|          16 | Plant & Animal Oil        |         1 |
|          17 | Potpourri                 |         1 |
|          18 | Raw Cotton & Cotton Waste |         1 |
|          19 | Rice                      |         1 |
|          20 | Tea                       |         1 |
|          21 | Seeds                     |         1 |
|          22 | Vegetable                 |         1 |
|          30 | Activated Carbon          |         3 |
+-------------+---------------------------+-----------+