2011-08-24 76 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 | 
+-------------+---------------------------+-----------+ 
相關問題