MySQL按固定位置排序

时间:2015-05-27 18:13:06

标签: mysql sql-order-by

我有一个名为fixed_position的列表。对于某些项目,这将填充int,其他行具有空值。

我正在运行以下查询:

fixed_position=12

因此结果按intvalue DESC排序。但我希望在结果集中第12个位置始终有+------+-------------------+-------------+ | ID | fixed_position | intvalue | +------+-------------------|-------------+ | x | null | 17 | | x | null | 14 | | x | null | 11 | | x | null | 9 | | x | 3 | 6 | | x | 2 | 3 | | x | null | 1 | 行。

这可能,我该怎么做?

示例数据:

+------+-------------------+-------------+
|  ID  | fixed_position    |   intvalue  |
+------+-------------------|-------------+
|  x   |       null        |       17    |
|  x   |        2          |       3     |
|  x   |        3          |       6     |
|  x   |       null        |       14    |
|  x   |       null        |       11    |
|  x   |       null        |       9     |
|  x   |       null        |       1     |

期望的输出:

let o1 : IObservable<int option> = // ...
let o2 = Observable.choose id o1

3 个答案:

答案 0 :(得分:0)

CASE子句中使用ORDER BY语句为fixed_position null case分配更高的排序值,以便它们浮动到列表的底部。例如:

ORDER BY (CASE WHEN intvalue IS NULL then 999 ELSE 0 END)

答案 1 :(得分:0)

您是否尝试使用ROW_NUMBER()OVER(按顺序“可以使用case语句更新,以更新fixedposition = 12,其中行号= 12

运行此作为临时查询

答案 2 :(得分:0)

你的要求有点奇怪。但你可以试试这个:

set @pos =0; 
select * from (
 SELECT @pos := @pos +1 pos, id, intvalue, fixed_position
 from (select id, fixed_position, id+11 as intvalue
   FROM content_items
   ORDER BY intvalue DESC)
  e
 ) f
 order by case when fixed_position>0 then fixed_position else pos end;

它仍然无法按您的要求运行。它只是给你一个更接近的订单。要获得更接近的订单,您需要将具有您自己定义的位置中的计算订单的所有条目移动到底部(或至少移动到最后预定义的位置)。