又一个复杂的MySQL排序

时间:2011-01-26 16:35:26

标签: sql mysql sorting

我搜索了SO的答案,但似乎我的具体情况与其他情况略有不同。

基本上我的数据包含一些带有“位置”的“主”记录(RoR中的acts_as_list),然后是任意数量的“自定义”记录,其中包含一个用于镜像主位置的custom_position。所需的结果是检索包含master + custom记录的集合,由master1,custom1 ...,master2,custom2 ...,

排序

主记录将具有NULL custom_position;自定义记录的custom_position等于其主人的位置。

源数据,未分类:

name        sort_a   sort_b
====        ======   ======
Lorem       1        NULL
ipsum       2        NULL
dolor       3        NULL
Lorem foo   4        1
ipsum foo   5        2
dolor foo   6        3
Lorem bar   7        1
ipsum bar   8        2
dolor bar   9        3
Lorem duck  10       1
ipsum duck  11       2
dolor duck  12       3

所需的排序:

name        sort_a   sort_b
====        ======   ======
Lorem       1        NULL
Lorem foo   4        1
Lorem bar   7        1
Lorem duck  10       1
ipsum       2        NULL
ipsum foo   5        2
ipsum bar   8        2
ipsum duck  11       2
dolor       3        NULL
dolor foo   6        3
dolor bar   9        3
dolor duck  12       3

最接近我:   通过合并(sort_a,sort_b)asc

订购
name        sort_a   sort_b
====        ======   ======
Lorem foo   4        1
Lorem bar   7        1
Lorem duck  10       1
Lorem       1        NULL
ipsum foo   5        2
ipsum bar   8        2
ipsum duck  11       2
ipsum       2        NULL
dolor foo   6        3
dolor bar   9        3
dolor duck  12       3
dolor       3        NULL

知道如何在ORDER BY子句中实现所需的排序吗?

2 个答案:

答案 0 :(得分:5)

SELECT  *
FROM    mytable
ORDER BY
        COALESCE(sort_b, sort_a), sort_a

要检查的查询:

SELECT  *
FROM    (
        SELECT  'Lorem' AS name, 1 AS sort_a, NULL AS sort_b
        UNION ALL
        SELECT  'ipsum' AS name, 2 AS sort_a, NULL AS sort_b
        UNION ALL
        SELECT  'dolor' AS name, 3 AS sort_a, NULL AS sort_b
        UNION ALL
        SELECT  'Lorem foo' AS name, 4 AS sort_a, 1 AS sort_b
        UNION ALL
        SELECT  'ipsum foo' AS name, 5 AS sort_a, 2 AS sort_b
        UNION ALL
        SELECT  'dolor foo' AS name, 6 AS sort_a, 3 AS sort_b
        UNION ALL
        SELECT  'Lorem bar' AS name, 7 AS sort_a, 1 AS sort_b
        UNION ALL
        SELECT  'ipsum bar' AS name, 8 AS sort_a, 2 AS sort_b
        UNION ALL
        SELECT  'dolor bar' AS name, 9 AS sort_a, 3 AS sort_b
        UNION ALL
        SELECT  'Lorem duck' AS name, 10 AS sort_a, 1 AS sort_b
        UNION ALL
        SELECT  'ipsum duck' AS name, 11 AS sort_a, 2 AS sort_b
        UNION ALL
        SELECT  'dolor duck' AS name, 12 AS sort_a, 3 AS sort_b
        ) q
ORDER BY
        COALESCE(sort_b, sort_a), sort_a

答案 1 :(得分:0)

这有点棘手,但可以使用UNION完成。第一个子句用于NULL行,第二个子句用于其他子句:

select name
     , sort_a
     , sort_a as sort_b
  from myTable
 where sort_b is null
 UNION ALL
select name
     , sort_a
     , sort_b
  from myTable
 where sort_b is NOT null
 order by 3,2

请注意,在UNION查询中,您使用列号而不是名称进行排序。