简体   繁体   English

SQLAlchemy order_by自定义排序?

[英]Sqlalchemy order_by custom ordering?

I have a state column in my table which has the following possible values: discharged , in process and None . 我的表中有一个state列,该列具有以下可能的值: dischargedin processNone

Can I fetch all the records in the following order: in process , discharged followed by None ? 我是否可以按以下顺序获取所有记录: in process ,先discharged ,再discharged None

If you've declared that column as an enum type (as you should for cases such as these where the values are drawn from a small, fixed set of strings), then using ORDER BY on that column will order results according to the order in which the values of the enum were declared. 如果您已将该列声明为枚举类型(例如,对于这样的情况,即这些值是从固定的小型字符串集中得出的),则在该列上使用ORDER BY将根据结果的顺序进行排序声明了枚举的值。 So the datatype for that column should be ENUM('in process', 'discharged', 'None') ; 因此该列的数据类型应为ENUM('in process', 'discharged', 'None') ; that will cause ORDER BY to sort in the order you desire. 这将导致ORDER BY按照您想要的顺序排序。 Specifically, each value in an enum is assigned a numerical index and that index is used when comparing enum values for sorting purposes. 具体来说,枚举中的每个值都分配有一个数字索引,并且在比较枚举值以进行排序时会使用该索引。 (The exact way in which you should declare an enum will vary according to which type of backend you're using.) (声明枚举的确切方式将根据所使用的后端类型而有所不同。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM