在sqlalchemy核心中使用IFNULL

时间:2015-07-31 21:23:23

标签: python mysql sqlalchemy

我正在尝试使用mysqlIFNULL表中使用sqlalchemy核心选择行。

给出一个像这样的表:

id    int1    string1   other
1      7        NULL    other stuff
2      NULL     bar     more stuff 

sql会是这样的:

SELECT IFNULL(int1, 0) AS int1, IFNULL(string1, '') AS string1 FROM table

这可能使用核心吗?什么会是伟大的将是像

s = select(ifnull(table.c.int1, 0), ifnull(table.c.string1, ''))

2 个答案:

答案 0 :(得分:3)

你应该可以使用sqlalchemy.sql中的func来实现任意数据库函数(我认为ifnull是db依赖的,我使用coalesce for postgresql):

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, '')])

答案 1 :(得分:1)

PostgreSQL不支持是否为空

可以使用func.coalesce()代替ifnull()

语法-

  func.coalesce(Table.field, default_value)

示例-

 func.coalesce(Order.price, 0)

 func.coalesce(Student.name, ' ')