【问题标题】:SQLAlchemy: coalesce() returning first not NULL and non-empty resultSQLAlchemy:coalesce() 首先返回非 NULL 和非空结果
【发布时间】:2015-02-15 22:56:55
【问题描述】:

我正在查询第一个非空用户名:

query = session.query(
    Account.id.label('acc_id'),
    Account.username.label('acc_username'),
    User.username.label('us_username'),
    User.another_username.label('also_username'),
    User.email.label('email')
).join(Account.user)

然后我在acc_usernameus_usernamealso_usernameemail 中搜索第一个非空值。为了做到这一点,我准备了一个函数来创建一个 KeyedTuple 从找到的 id 和第一个非空字符串值:

for q in query.all():
    account_tuple = KeyedTuple(
        [q.acc_id, q.acc_username or q.us_username or q.also_username or q.email or ''],
        labels=_LABELS)

但我宁愿使用某种形式的 coalesce,除了返回第一个非空值(在 Python 中首先是 not False 值)而不是 not NULL。有没有正确的方法来做到这一点?我非常感谢将所有这些逻辑保留在查询中,而不是在单独的函数中创建另一个 KeyedTuple

【问题讨论】:

    标签: python sqlalchemy coalesce


    【解决方案1】:

    我已经在 SQLAlchemy 中使用 MySQL case 方法处理了这个问题:

    query = session.query(
        Account.id.label('acc_id'),
        case(
            [
                (Account.username != '', Account.username),
                (User.username != '', User.username),
                (User.another_username != '', User.another_username),
                (User.email != '', User.email)
            ],
            else_='')
        .label('username')
        .join(Account.user)
    

    虽然这可能不是实现第一个非空字符串的正确方法(与空字符串的比较也拒绝 NULL 条目)它在这种情况下运行良好并且省略了第二个 @ 的创建987654324@.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      相关资源
      最近更新 更多