我有以下的,简单的表MySQL的结果集
Item (id, name, date, fixed_position)
(1, 'first entry', '2016-03-09 09:00:00', NULL)
(2, 'second entry', '2016-03-09 04:00:00', 1)
(3, 'third entry', '2016-03-09 05:00:00', NULL)
(4, 'fourth entry', '2016-03-09 19:00:00', NULL)
(5, 'fifth entry', '2016-03-09 13:00:00', 4)
(6, 'sixth entry', '2016-03-09 21:00:00', 2)
项目的数量是不固定的,其实可以改变从约100至约1000。
我想实现的是执行查询以返回由date
字段排序的项目集,该字段考虑了fixed_position
字段,该字段代表“固定”结果等特定位置。如果给定条目的fixed_position
不为NULL,则结果应该固定到第n个位置,并且如果fixed_position
为NULL,则ORDER BY
应该优先。
更亮解释查询所需的输出:
(2, 'second entry', '2016-03-09 04:00:00', 1) // pinned to 1-st position
(6, 'sixth entry', '2016-03-09 21:00:00', 2) // pinned to 2-nd position
(3, 'third entry', '2016-03-09 05:00:00', NULL) // ORDER BY `date`
(5, 'fifth entry', '2016-03-09 13:00:00', 4) // pinned to 4-th position
(1, 'first entry', '2016-03-09 09:00:00', NULL) // ORDER BY `date`
(4, 'fourth entry', '2016-03-09 19:00:00', NULL) // ORDER BY `date`
我试图解决方案张贴在Ordering MySql results when having fixed position for some items但即使复制粘贴的方法这似乎并没有在所有的工作。
我已经试过这一步是这个查询:
SELECT
@i := @i +1 AS iterator,
t.*,
COALESCE(t.fixed_position, @i) AS positionCalculated
FROM
Item AS t,
(
SELECT
@i := 0
) AS foo
GROUP BY
`id`
ORDER BY
positionCalculated,
`date` DESC
将返回:
iterator | id | name | date | fixed_position | positionCalculated
1 1 first entry 2016-03-09 09:00:00 NULL 1
2 2 second entry 2016-03-09 04:00:00 1 1
6 6 sixth entry 2016-03-09 21:00:00 2 2
3 3 third entry 2016-03-09 05:00:00 NULL 3
4 4 fourth entry 2016-03-09 19:00:00 NULL 4
5 5 fifth entry 2016-03-09 13:00:00 4 4
是否MySQL能够执行这样的任务,或者我应该采取后端的做法,并执行PHP两个的array_merge()
结果集?
什么是您正在使用的SQL?这样我们就可以看到你的尝试。 IE:按日期排序,ifnull(fixed_position,0)' –
我在我的问题中添加了示例查询。花了超过5小时寻找答案,几乎没有结果。 –
'fixed_position'是你表中的一个字段还是一个计算的字段? –