SQL表本身连接,但允许值为“ 0”

问题描述 投票:0回答:1

好,所以我在此表上有一个简单的表“ category”,并且保存了子类别。类别具有“ parent_id = 0”,子类别具有“ parent_id”,其等于类别的row_id。

例如

ID  name       parent_id
1   fruit      0
2   apple      1
3   pear       1
4   vegetable  0
5   tomato     4

Fruit
-apple
-pear
vegetable
-tomato

在此示例中,“水果”和“蔬菜”是其余子类别的类别,我知道在这一热门话题上已经有很多问题可以回答。但是我的问题是:

我如何加入“ ID”和“ parent_id”。目前,我使用的是“ xampp”,当我加入值时,xampp不允许:

parent_id = 0;

因为它与“ ID”的主键和外键链接。

sql foreign-keys self-join
1个回答
0
投票

[使用带有适当的ORDER BY子句的自我联接:

SELECT
    c1.name
FROM category c1
LEFT JOIN category c2
    ON c1.parent_id = c2.ID
ORDER BY
    COALESCE(c2.ID, c1.ID),
    c1.ID;
© www.soinside.com 2019 - 2024. All rights reserved.