我有一个非常标准的设置,想按一列排序:
someselect.order_by(asc(table1.mycol))
不过,我想用行''或NULL对mycol出现在结果的末尾。有没有办法做到这一点?
在支持的数据库上NULLS LAST,您可以NULL通过执行以下操作在末尾对 s进行排序
SELECT * FROM table1 ORDER BY mycol ASC NULLS LAST;
Run Code Online (Sandbox Code Playgroud)
您需要转换''为NULLs,以便可以在数据中或作为查询的一部分执行此操作(无论如何我建议这样做):
SELECT * FROM table1 ORDER BY (CASE mycol WHEN '' THEN NULL ELSE mycol END) ASC NULLS LAST;
Run Code Online (Sandbox Code Playgroud)
或者,一种更便携的方法是
SELECT * FROM table1 ORDER BY (CASE WHEN mycol IS NULL OR mycol = '' THEN 1 ELSE 0 END) ASC, mycol;
Run Code Online (Sandbox Code Playgroud)
要在 SQLAlchemy 中编写此内容:
.order_by(case([(or_(tabel1.mycol.is_(None), table1.mycol == ""), 1)],
else_=0), table1.mycol)
Run Code Online (Sandbox Code Playgroud)
SQLAlchemy具有表达式的NULLS LAST修饰符ORDER BY:
sqlalchemy.sql.expression.nullslast(column)
Run Code Online (Sandbox Code Playgroud)
参见http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.nullslast
| 归档时间: |
|
| 查看次数: |
1752 次 |
| 最近记录: |