我正在查询第一个非空用户名:
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_username
、us_username
、also_username
和 email
中的第一个非空值.为了做到这一点,我准备了一个函数来从找到的 id
和第一个非空字符串值创建一个 KeyedTuple
:
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
。
最佳答案
我已经使用 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
条目),但它在这种情况下效果很好并省略了第二个 KeyedTuple
的创建。
关于python - SQLAlchemy:coalesce() 首先返回非 NULL 和非空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27524825/