0

首先,抱歉标题不好。我有点着急,想不出更好的。

现在我有一张这样的桌子 -

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

4 回答 4

3

你想要一个表与自身的 JOIN:

SELECT child.name, parent.name FROM tbl AS child
    LEFT JOIN tbl AS parent
    ON (child.parent_category__id = parent.category_id);
于 2012-08-30T13:11:31.140 回答
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
于 2012-08-30T13:11:34.613 回答
1
SELECT   c.name  Name,
         p.name  ParentCategory
FROM  t  c
LEFT JOIN t  p 
ON p.category_id=c.parent_category_id;

看到这个 SQLFiddle

于 2012-08-30T13:15:16.157 回答
-1
SELECT t1.name, t2.name FROM table as t1 LEFT JOIN table as t2 ON t1.parent_category_id=t2.category_id
于 2012-08-30T13:11:44.930 回答