2011-08-24 112 views
0

什么是让所有的孩子类别所需的SQL我使用PostgreSQL的获取所有的子类别中的顶级类别

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

您是否需要仅在第一级获取类别,或者是深度级别的任意级别?你使用的是mysql还是postgresql?这很重要,因为postgre中有一个''递归'',这使得任务变得更容易 – J0HN

回答

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 | 
+-------------+---------------------------+-----------+ 
相关问题