2010-05-22 59 views
1

我有表,這樣的價值觀,mysql通過單個查詢獲取結果父ID和類別ID?

CREATE TABLE `category` (
`id` INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY , 
`category` VARCHAR(50) NOT NULL , 
`parent` INT(4) NOT NULL 
) 

INSERT INTO `category` VALUES (1, 'MCA', 9); 
INSERT INTO `category` VALUES (2, 'M Tech', 9); 
INSERT INTO `category` VALUES (3, 'B Tech', 9); 
INSERT INTO `category` VALUES (4, 'BioTech', 9); 
INSERT INTO `category` VALUES (5, 'InfoTech', 9); 
INSERT INTO `category` VALUES (6, 'Chemical', 10); 
INSERT INTO `category` VALUES (7, 'Indus', 10); 
INSERT INTO `category` VALUES (8, 'Physics', 10); 
INSERT INTO `category` VALUES (9, 'Information Science', 0); 
INSERT INTO `category` VALUES (10, 'Others Science', 0); 

我需要的類別和子類別方面獲得的值的單個查詢。第三個值爲零,其他類別爲子類別。

我需要輸出爲樹狀結構這樣,

結果是:

Information Science 
    MCA 
    M Tech 
    B Tech 
    BioTech 
    InfoTech 
Others Science 
    Chemical 
    Indus 
    Physics 
+0

這是措辭有點笨拙,也許你需要輸出的一個例子將是有用的? – Farthingworth 2010-05-22 10:12:15

回答

1

也許這是你想要什麼:

SELECT 
    T1.category AS category, 
    T2.category AS subcategory 
FROM category T1 
JOIN category T2 
ON T1.id = T2.parent 
 
category    subcategory 
'Information Science' 'MCA' 
'Information Science' 'M Tech' 
'Information Science' 'B Tech' 
'Information Science' 'BioTech' 
'Information Science' 'InfoTech' 
'Others Science'  'Chemical' 
'Others Science'  'Indus' 
'Others Science'  'Physics' 

這是假設只有你在你的層次結構中有兩個層次。

+0

可能不會返回沒有子類別 – 2010-05-22 13:03:56

2

Mysql有一個nice article for you。 雖然個人,我會去物化路徑

+0

的類別將檢查並告訴此... – Karthik 2010-07-15 04:22:32