MySQL-从同一个表中获取多个记录

时间:2012-08-30 13:08:30

标签: mysql

首先,抱歉标题不好。我匆匆忙忙,想不出更好的一个。

现在我有一张这样的表 -

category_id    name        parent_category_id
______________________________________
1              country     0
2              state       1
3              city        2
4              block       3

我希望结果为 -

Name        ParentCategory
___________________________
country     NULL
state       country
city        state
block       city

现在逻辑是ParentCategory是类别名称,其category_id等于parent_category_id。 (不确定我是否正确解释了)我尝试了很多为此编写查询,但不知道我该怎么做。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:3)

你想要自己加入表:

SELECT child.name, parent.name FROM tbl AS child
    LEFT JOIN tbl AS parent
    ON (child.parent_category__id = parent.category_id);

答案 1 :(得分:3)

SELECT 
  child.name AS Name,
  parent.name AS ParentCategory
FROM
  yourTableName AS child
  LEFT JOIN yourTableName AS parent ON parent.category_id=child.parent_category_id

答案 2 :(得分:1)

SELECT   c.name  Name,
         p.name  ParentCategory
FROM  t  c
LEFT JOIN t  p 
ON p.category_id=c.parent_category_id;

See this SQLFiddle

答案 3 :(得分:-1)

SELECT t1.name, t2.name FROM table as t1 LEFT JOIN table as t2 ON t1.parent_category_id=t2.category_id