【问题标题】:MySql select query for same table category and subcategory parent under childMySql选择查询相同表类别和子类别下的子类别父
【发布时间】:2022-01-05 11:54:51
【问题描述】:

这个问题已经问过了,但这并不能解决我的问题。

我在表名categories 下面给出了一个表,这里parentchild 插入同一个表。我想获取父类下的所有子类。

我的桌子:

categoryId   categoryName      categorytype  parentCategoryId   status
1            cars                   0              0                1
2            honda city             1              1                1
3            Medical                0              0                1
4            Cancer                 1              4                1
5            bmw                    1              1                1

所以我想获取这样的数据输出:

categoryId   categoryName        parentCategoryId
1            cars                        0       
2            honda city                  1       
5            bmw                         1      
3            Medical                     0       
4            Cancer                      4      

我正在尝试做的是carparent 在此所有汽车名称下都会列出。

这是我尝试过的查询:

SELECT * FROM categories c1 left join categories c2 on c2.categoryId = c1.parentCategoryId;

【问题讨论】:

  • 看起来您的查询仅缺少 ORDER BY 子句
  • @ProGu:是的,我试过ORDER by c1.categoryId,但问题是所有名称都没有正确列出
  • @ProGu:你可以看到这个ibb.co/x2PjFWd这里HIV是一个不属于medical类别的孩子

标签: php mysql sql select


【解决方案1】:

这个可以用

SELECT c1.* 
FROM categories c1 
LEFT JOIN categories c2 on c2.categoryId = c1.parentCategoryId
ORDER BY COALESCE(c2.categoryId, c1.categoryId), c1.categoryId

编辑

如果根类别是固定的0,没有JOIN会更简单

SELECT *
FROM categories
ORDER BY CASE WHEN parentCategoryId = 0 THEN categoryId ELSE parentCategoryId END, categoryId

【讨论】:

    猜你喜欢
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    相关资源
    最近更新 更多