如何显示自我指向表?

时间:2017-12-08 16:33:25

标签: c# mysql sql asp.net mariadb

我有一个名为category的表。某些类别是其他类别的子类别。

--------------------------
ID | Name | Upper_Category
--------------------------

Upper_Category引用其他类别ID 我需要像这样显示表格:

ID | Name    | Upper_Category
1  | ROOT #1 | NULL
5  | exam #2 | 1
7  | exam #3 | 1
4  | ROOT #2 | NULL
9  | exam #4 | 4
2  | exam #5 | 4
3  | exam #6 | 4
6  | ROOT #3 | NULL
...

首先显示Upper_CategoryNULL的类别,然后显示引用它们的子类别。

我通过使用JOINS和UNION尝试了很多,但没有成功。

2 个答案:

答案 0 :(得分:1)

case子句中需要order by

select *
from table1
order by case when Upper_Category is null then id else upper_category end, upper_category

<强>结果:

+----+---------+----------------+
| ID |  Name   | Upper_Category |
+----+---------+----------------+
|  1 | ROOT #1 | NULL           |
|  5 | exam #2 | 1              |
|  7 | exam #3 | 1              |
|  4 | ROOT #2 | NULL           |
|  9 | exam #4 | 4              |
|  2 | exam #5 | 4              |
|  3 | exam #6 | 4              |
|  6 | ROOT #3 | NULL           |
+----+---------+----------------+

<强> DEMO

答案 1 :(得分:1)

如果可以有多个级别的类别,则可以使用here

WITH RECURSIVE r1 AS (
    SELECT * FROM t1 WHERE upper_category IS NULL
    UNION
    SELECT t1.* FROM t1, r1 WHERE r1.id = t1.upper_category)
SELECT * FROM r1;

+------+---------+----------------+
| id   | data    | upper_category |
+------+---------+----------------+
|    1 | ROOT #1 |           NULL |
|    4 | ROOT #2 |           NULL |
|    6 | ROOT #3 |           NULL |
|    5 | exam #2 |              1 |
|    7 | exam #3 |              1 |
|    9 | exam #4 |              4 |
|    2 | exam #5 |              4 |
|    3 | exam #6 |              4 |
+------+---------+----------------+