在一次寫業務的過程當中,發如今使用 sql 查詢數據的時候,不是按照我但願的順序進行排序的,而是根據系統順序進行排序的.o(╥﹏╥)opython
SELECT * FROM table_name WHERE id in (3,4,1,2)
我覺得不加ORDER BY
進行排序也會根據給定的順序輸出數據,太想固然了!sql
# FIELD SELECT * FROM table_name WHERE id in (3,4,1,2) ORDER BY FIELD (須要排序的字段,自定義的順序) # 根據 id 進行排序,自定義的順序爲 2,3,1,4 SELECT * FROM table_name WHERE id in (3,4,1,2) ORDER BY FIELD (id,2,3,1,4) # INSTR # 按照 id 的 2,4,1,3 順序進行排序 SELECT * FROM table_name WHERE id in (3,4,1,2) ORDER BY INSTR('2,4,1,3',id) # LOCATE SELECT * FROM table_name WHERE id in (1,2,3,4) ORDER BY LOCATE(id,'2,4,3,1')
# SQL 函數能夠拼接 sql 語句 from peewee import SQL # ids是一個 list ids= [2,3,4,1] str_ids = ",".join(ids) query = MyModel.select().where(MyModel.id << ids).order_by(SQL('field(id,%s) % str_ids'))