3

我似乎无法弄清楚如何在这个 MySQL 选择中排序。我希望你能帮助我。

表格:

类别

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

类别翻译

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

langId, langName, langCode
1       Danish    da
2       English   en

我的查询:

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'

现在,我得到了我想要的东西,但是有没有办法将子类别排序给他们的父母,所以结果如下所示:

期望的结果:

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

我试过order by,但似乎可以得到我想要的结果。

4

3 回答 3

2

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.

于 2012-10-18T18:27:18.930 回答
2

你不能得到你喜欢的结果,因为它不可能。我看不到允许按您想要的方式订购的模式或 ID。

为什么标题 4、标题 5 先上?

我看不到逻辑。也许示例不完整,也许 CatName 和 CatDesc 的顺序是您需要的关键。

于 2012-10-18T18:18:41.743 回答
-3
ORDER BY catParentID, catID, ...
于 2012-10-18T18:14:13.020 回答