2016-11-05 38 views
5

我的類別表正在尋找類似如下:如何在MySQL的單個查詢中選擇所有sub_category記錄及其main_category_name和parent_id?

------------------------------------ 
id | name   | parent_id | 
------------------------------------ 
1 | Vehicles  | 0   | 
2 | Car Insurance | 1   | 
3 | Van Insurance | 1   | 
4 | PhoneRecharge | 0   | 
5 | prepaid  | 4   | 
6 | postpaid  | 4   | 

輸出應該如下所示:

--------------------------------------------------------- 
id | parent_id | main_category_name | sub_category_name| 
--------------------------------------------------------- 
2 | 1  | Vehicles   | Car Insurance | 
3 | 1  | Vehicles   | Van Insurance | 
5 | 4  | PhoneRecharge | prepaid   | 
6 | 4  | PhoneRecharge | postpaid   | 

如需獲取上述記錄,我需要儘量減少我的數據庫交互。所以我需要在單個查詢中實現上述數據。

+0

難道只是我,還是不要了ID的比賽了一個和對方?向我們顯示您執行的查詢以獲取所需的數據。 – Xorifelse

+0

選擇catg.''',cat.''',cat.'''作爲'main_cat_name',catg.'''作爲'sub_catagory_name' FROM 'Catagory' cat,'catagory' catg WHERE cat.' id' = catg.'parent_id' 使用以下陳述的查詢@Xorifelse – smondal345

回答

2

這應該工作:

SELECT 
    c.id AS cat_id, 
     parent.id AS parent_id, 
    parent.name AS main_category_name, 
    c.name AS sub_category_name 
FROM 
    category c JOIN category parent ON c.parent_id = parent.id 
相關問題