SQLAlchemy核心表达式 - COALESCE和CASE

时间:2015-11-25 20:16:47

标签: python sqlalchemy case coalesce

我尝试生成与此SQL对应的Core表达式:https://dba.stackexchange.com/a/122116/47472

但是,这个表达式失败了:

q = select([
    component,
    base_vee,
    case(
        [
            (coalesce(base_vee.c.affidavit, '') == '')
        ],
        else_=True).label('emptyish')
    ]). \
    where(
        and_(
            component.c.id.in_(comp_ids),
            component.c.id == base_vee.c.component_id,
            base_vee.c.type == 'typical',
        )
    )

例外:

  File "/export/home/myuser/mysite/mysite/afile.py", line 527, in afunc
    else_=True).label('emptyish')
  File "<string>", line 2, in case
  File "/export/home/myuser/mysite/ve/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 2187, in __init__
    _literal_as_binds(r)) for (c, r) in whens
  File "/export/home/myuser/mysite/ve/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 343, in __getitem__
    return self.operate(getitem, index)
  File "/export/home/myuser/mysite/ve/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 739, in operate
    return op(self.comparator, *other, **kwargs)
  File "/export/home/myuser/mysite/ve/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 343, in __getitem__
    return self.operate(getitem, index)
  File "<string>", line 1, in <lambda>
  File "/export/home/myuser/mysite/ve/lib/python2.7/site-packages/sqlalchemy/sql/type_api.py", line 60, in operate
    return o[0](self.expr, op, *(other + o[1:]), **kwargs)
  File "/export/home/myuser/mysite/ve/lib/python2.7/site-packages/sqlalchemy/sql/default_comparator.py", line 166, in _unsupported_impl
    "this expression" % op.__name__)

当我删除case表达式(仅留下coalesce)时,它可以正常工作。但我无法让Core接受case

如何使其与case一起使用?

1 个答案:

答案 0 :(得分:0)

原来它是“RTFM小心”的情况:

    case(
        [
            (coalesce(base_vee.c.affidavit, '') == '', False)
        ],
        else_=True).label('emptyish')
    ])