我有一个名为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_Category
为NULL
的类别,然后显示引用它们的子类别。
我通过使用JOINS和UNION尝试了很多,但没有成功。
答案 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 |
+------+---------+----------------+