dongtangu6144 2012-10-18 18:10
浏览 402
已采纳

带有多个INNER JOIN的MySQL ORDER BY

I can't seem to figure out how to order by in this MySQL select. I hope you can help me out.

Tabels:

categories

catId, catParentId, catDisplay
1      0            1
2      0            1
3      0            1
4      1            1
5      1            1

categories_translation

transId, catId, catName, catDesc, langId
1        1      Title1   Desc1    1
2        2      Title2   Desc2    1
3        3      Title3   Desc3    1
4        4      Title4   Desc4    1
5        5      Title5   Desc5    1

language

langId, langName, langCode
1       Danish    da
2       English   en

My query:

SELECT `categories`.`catId`,
       `categories`.`catParentId`,
       `categories`.`catDisplay`,
       `categories_translation`.`catName`,
       `categories_translation`.`catDesc`,
       `language`.`langCode`
FROM   `categories`
INNER JOIN `categories_translation` ON `categories_translation`.`catId` = `categories`.`catId`
INNER JOIN `language` ON `language`.`langId` = `categories_translation`.`langId`
WHERE `language`.`langCode` = 'da'

Now, I get returned what I want, but is there a way to order the child categories to their parents, so the result looks like this:

Desired result:

catId | catParentId | catDisplay | catName | catDesc | langCode
1       0             1            Title1    Desc1     da
4       1             1            Title4    Desc4     da
5       1             1            Title5    Desc5     da
2       0             1            Title2    Desc2     da
3       0             1            Title3    Desc3     da

I've tried order by, but can seem to get the results like I want.

  • 写回答

3条回答 默认 最新

  • douzi9744 2012-10-18 18:27
    关注

    Try the following:

    ORDER BY
        CASE WHEN categories.catParentId = 0 THEN
            categories.catId
        ELSE 
            categories.catParentId
        END,
        CASE WHEN categories.catParentId = 0 THEN
            0
        ELSE
            categories.catId
        END
    

    For those that don't get the ordering it would be easier to think of the desired result as:

    catId | catParentId | orderingCategory
    1       0             1.0
    4       1             1.4
    5       1             1.5
    2       0             2.0
    3       0             3.0
    

    So it's a hierarchy of categories, OP wants to order the result so that each parent categories are followed by their child categories.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题