mysql通过单个查询获取结果父ID和类别ID?

时间:2010-05-22 10:05:08

标签: mysql

我有这样的表和值,

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);

我需要一个查询来获取类别和子类别的值。第3个值为零,其他为子类别。

我需要输出像这样的树结构,

结果是:

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

2 个答案:

答案 0 :(得分:2)

Mysql有一个 nice article for you 。 虽然我亲自去了物化路径

答案 1 :(得分: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'

这假设您的层次结构中只有两个级别。