需要SQL查询的帮助

时间:2011-04-28 03:01:07

标签: sql hierarchical-data

我有一个具有以下结构的表 -

Category {Id, Name, ParentId}

我有这样的价值观 -

id  name               parentid
-------------------------------
1   Technology Focus   NULL
2   Tools              1
3   Database           1

如何编写显示如下的查询 -

name (parent)      name (child)             
--------------------------------
Technology Focus   Tools
Technology Focus   Database
etc..

我相信我需要使用Group By子句,但我不太明白。谢谢你的帮助。

3 个答案:

答案 0 :(得分:6)

如果我正确看待,我认为你只需要

select parent.name, child.name 
from category child
  inner join category parent
    on parent.id = child.parentid

答案 1 :(得分:1)

您需要像这样加入表格:

select Cat.Name, Par.Name
from category as cat
inner join category par on cat.id = par.id

答案 2 :(得分:1)

如果你试图在SQL中实现类似树的结构,那么这种做法是错误的。

您应该使用两个表来实现树:

CREATE TABLE Categories (
   category_id INT AUTO_INCREMENT,
   name VARCHAR(40),
   PRIMARY KEY (category_id)
);
CREATE TABLE Tree (
   ancestor INT NOT NULL,
   descendant INT NOT NULL,
   PRIMARY KEY(ancestor, descendant),
   FOREIGN KEY (ancestor) REFERENCES Categories(category_id),
   FOREIGN KEY (descendant) REFERENCES Categories(category_id)
);

此结构(称为 Closure Table )更易于维护(预先更新,重新排列结构等)。

然后选择如下数据:

SELECT 
   parent.name AS parent,
   item.name AS item
FROM Categories AS parent
LEFT JOIN Tree AS path ON parent.category_id = path.ancestor
LEFT JOIN Categories AS item ON item.category_id = path.descendant
WHERE parent.category_id = 1

无论如何,阅读 Closure Tables ,你会理解为什么......