【问题标题】:Using IFNULL in sqlalchemy core在 sqlalchemy 核心中使用 IFNULL
【发布时间】:2015-07-31 21:23:23
【问题描述】:

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

给定一张这样的表格:

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

【问题讨论】:

    标签: python mysql sqlalchemy


    【解决方案1】:

    PostgreSQL 不支持 if null

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

    语法-

      func.coalesce(Table.field, default_value)
    

    示例 -

     func.coalesce(Order.price, 0)
    
     func.coalesce(Student.name, ' ')
    

    【讨论】:

      【解决方案2】:

      您应该能够像这样将 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, '')])
      

      【讨论】:

      • 你用的是什么版本?我正在使用 SQLAlchemy==1.0.5,我认为 func 至少从 0.4 开始就已经存在了。
      猜你喜欢
      • 2014-02-08
      • 2016-06-24
      • 2019-06-07
      • 2017-01-13
      • 2019-09-03
      • 2021-09-09
      • 2022-11-10
      • 2011-12-17
      • 2015-06-04
      相关资源
      最近更新 更多