我有以下代码来获取要呈现给用户的项目:
SELECT * FROM main_cue WHERE group_id IN (1,2,3,4) GROUP BY group_id;
>>> 1,2,3,4
但是,我想为此提供一个特定的顺序,这样(1)我有一个要推送到堆栈末尾的项目列表按照我指定的确切顺序和(2) )不在列表中的项目将由id ASC订购。例如:
items_to_push_to_end_of_stack_in_this_exact_order = [3,2]
新的排序将是:
>>> [1,4,3,2]
1) 1 # first item by ID asc, not in `items_to_push_to_end_of_stack_in_this_exact_order`
2) 4 # second item by ID asc, not in `items_to_push_to_end_of_stack_in_this_exact_order`
3) 3 # items_to_push_to_end_of_stack_in_this_exact_order
4) 2 # items_to_push_to_end_of_stack_in_this_exact_order
我如何在mysql中执行此操作?
答案 0 :(得分:1)
如果您尝试指定排序,请使用order by
:
ORDER BY
// First, Put "2" and "3" at the end of the stack
(group_id IN (2, 3)) ASC,
// Second, order the items not in the list by the `group_id`
(CASE WHEN group_id NOT IN (2, 3) THEN group_id END) ASC,
// Third, order the items in the list by the ordering you specify
FIELD(group_id, 3, 2)
这有点复杂。第一个条款将" 2"和" 3"在末尾。第二个按group_id
排序其余部分。第三个按照您指定的顺序对最后一个订单进行排序。
答案 1 :(得分:0)
使用戈登的答案和我目前的代码,这是有效的:
passed_on_group_ids_as_str = ','.join(passed_on_group_ids) # convert the list to csv
cues_per_group = Cue.objects.raw('''SELECT * FROM main_cue WHERE group_id IN %s GROUP BY group_id
ORDER BY (group_id IN (%s)) ASC,
(CASE WHEN group_id NOT IN (%s) THEN group_id END) ASC,
FIELD(group_id, %s)''',
(group_ids, passed_on_group_ids_as_str, passed_on_group_ids_as_str, passed_on_group_ids_as_str))