是否可以通过参数动态定义ORDER BY字段?通过不懈的搜索,我想出了你做不到的事情。
所以我想我会问你能不能?或者,如果有工作要做吗?
示例:
simple_token_authentication
作品
sql = "SELECT `xyz` FROM `checkins` WHERE `name`=%s AND `timestamp` >=%s AND `timestamp` < %s ORDER BY `xyz` DESC LIMIT 1"
query.execute(sql, (name, start, end))
不起作用
目标是使ORDER BY字段动态定义(使用字段变量),但是当我尝试动态定义时,它会不断返回未知字段或忽略该字段,因为它将其更改为“defined_field”引号
我试过从ORDER BY中删除`
答案 0 :(得分:0)
对于类似这样的事情,我对%s有偏见。你可以尝试:
name = 'kbball'
start = '2017'
end = '2018'
field = 'field'
sql = "SELECT `xyz` FROM `checkins` WHERE `name`= " + name + " AND `timestamp` >= " + start + " AND `timestamp` < " + end + " ORDER BY `"+ field + "` DESC LIMIT 1"
print(sql)
#output SELECT `xyz` FROM `checkins` WHERE `name`= kbball AND `timestamp` >= 2017 AND `timestamp` < 2018 ORDER BY `field` DESC LIMIT 1