选择特定层次结构内的文章

时间:2014-09-09 09:32:47

标签: sql sql-server

我有一个文章类别的表格,如下所示:


| Id | ParentId | Name
| 6  | 1        | Something else
| 5  | 2        | Mice
| 4  | 2        | Keyboards
| 2  | 1        | Computer accesories
| 1  | 0        | All

作为第二篇文章:

| Id | CategoryId | Name
| 1  | 4          | Simple keyboard
| 2  | 5          | Simple mouse
| 3  | 6          | Simple nothing

Article.CategoryId - > Category.Id

Category.ParentId - > Category.Id

现在我需要选择所有作为计算机配件的文章。这该怎么做?我试图做一些递归查询,但没有做任何工作。

预期结果是:

| 1 | Simple keyboard
| 2 | Simple mouse

由于他们的类别指向一个类别,该类别的父类别为ID 2,我正在搜索

2 个答案:

答案 0 :(得分:2)

试试这个:

SQL Fiddle

MS SQL Server 2012架构设置

CREATE TABLE Category
(
  ID INT,
  ParentId INT,
  Name VARCHAR(255)
)

CREATE TABLE Article
(
  ID INT,
  CategoryId INT,
  Name VARCHAR(255)
)

INSERT INTO Category 
VALUES
  (6,1, 'Something Else'),
  (5,2, 'Mice'),
  (4,2, 'Keyboards'),
  (2,1,'Computer Accessories'),
  (1, 0, 'All')


INSERT INTO Article
VALUES
  (1,4,'Simple keyboard'),
  (2,5,'Simple mouse'),
  (3,6,'Simple nothing')

查询1

;WITH CTE
AS
(
  SELECT ID, ParentId, Name
  FROM Category
  WHERE Name = 'Computer Accessories'

  UNION ALL

  SELECT c1.ID, c1.ParentId, c1.Name
  FROM Category c1
  INNER JOIN CTE c2
    ON c1.ParentId = c2.Id
)
SELECT Article.Id, Article.Name
FROM CTE
INNER JOIN Article
  ON Article.CategoryId = CTE.Id

<强> Results

| ID |            NAME |
|----|-----------------|
|  1 | Simple keyboard |
|  2 |    Simple mouse |

答案 1 :(得分:0)

我认为你正在寻找这个:

SELECT * FROM
Categories C
LEFT JOIN
Articles A
ON C.Id = A.CategoryId
WHERE C.Name = "Computer Accessories"

这将选择“计算机配件”作为名称 - 它具有分配给它的ID,即2.通过连接,它将显示所有具有类别ID 2的文章。