Luk*_*uke 3 python mysql sqlalchemy
我正在尝试使用sqlalchemy core从mysql表中选择行IFNULL。
给定这样的表:
id int1 string1 other
1 7 NULL other stuff
2 NULL bar more stuff
Run Code Online (Sandbox Code Playgroud)
的SQL将是这样的:
SELECT IFNULL(int1, 0) AS int1, IFNULL(string1, '') AS string1 FROM table
Run Code Online (Sandbox Code Playgroud)
使用内核可以吗?很棒的事情像
s = select(ifnull(table.c.int1, 0), ifnull(table.c.string1, ''))
Run Code Online (Sandbox Code Playgroud)
您应该能够像这样将 sqlalchemy.sql 中的 func 用于任意数据库函数(我认为 ifnull 依赖于 db,我对 postgresql 使用了 coalesce):
from sqlalchemy.sql import select, func
# assuming you have imported table from somewhere!!
s = select([func.ifnull(table.c.int1, 0), func.ifnull(table.c.string1, '')])
Run Code Online (Sandbox Code Playgroud)
PostgreSQL不支持是否为null
可以使用func.coalesce()代替ifnull()
句法 -
func.coalesce(Table.field, default_value)
Run Code Online (Sandbox Code Playgroud)
范例-
func.coalesce(Order.price, 0)
func.coalesce(Student.name, ' ')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3886 次 |
| 最近记录: |