对于一个网页来说,一个表格有多个排序选项是很常见的。现在我有一个案例,其中有 12 个选项(可排序的列)。最简单(据我所知)的方法是构建连接字符串的 SQL 查询。但我想知道这是否是最好的方法。字符串连接是这样的(python 代码):
order = {
1: "c1 desc, c2",
2: "c2, c3",
...
12: "c10, c9 desc"
}
...
query = """
select c1, c2
from the_table
order by %(order)s
"""
...
cursor.execute(query, {'order': AsIs(order[order_option])})
...
order by
到目前为止,我的替代解决方案是在子句中放置一系列案例:
select c1, c2
from the_table
order by
case %(order_option)s
when 1 then array[c1 * -1, c2]
when 2 then array[c2, c3]
else [0.0, 0.0]
end
,
case %(order_option)s
when 3 then c4
else ''
end
,
...
,
case when %(order_option)s < 1 or %(order_option)s > 12 then c5 end
;
关于多种订购选择的最佳做法是什么?我的替代代码中的索引利用率会怎样?