Python 将项目推至堆栈末尾(第2部分)

Python 将项目推至堆栈末尾(第2部分),python,mysql,Python,Mysql,我有以下代码,用于获取要呈现给用户的项目: 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]

我有以下代码,用于获取要呈现给用户的项目:

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中如何执行此操作?

如果您试图指定排序,请使用
orderby

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”。第二个按
组id
排序其余的。第三个按您指定的顺序对最后一组进行排序。

使用Gordon的答案和我目前掌握的代码,这就是有效的方法:

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))

@Cfreak的可能重复我认为上述问题不仅仅是使用其他问题和答案使用的
按字段排序(something)
。这更像是一种复合排序,与其他方法一起使用。