SQLAlchemy - 复制计数器列

时间:2014-03-18 11:20:17

标签: sqlalchemy

我需要一些帮助才能将以下查询转换为一个SQLAlchemy语句:

select c.id, 
c.first_name, 
c.middle_name, 
c.last_name,
cd.dups -- THIS IS A COLUMN WHICH IS NOT MAPPED THROUGH SQLAlchemy
from contacts c
inner join
(select _c.last_name, count(_c.last_name) as dups from contacts _c group by _c.last_name) cd on c.last_name = cd.last_name
group by c.id, c.first_name, c.last_name, cd.dups

修改-1: 忘了提到我正在使用我的Contact对象映射到contacts表的ORM。我会更具体地说明我想要实现的目标。根据特定条件选择联系人时,我必须返回一个额外的列'表示在联系人表格中找到last_name的次数。

1 个答案:

答案 0 :(得分:0)

如何使用标记列很难。

subq = self.db_context.query(Contact._last_name, label('dups', func.count(Contact._last_name))) \
                .group_by(Contact._last_name) \
                .subquery('dup_contacts')
            dup_contacts = aliased(Contact, subq)

            contacts = self.db_context.query(Contact, 'dups').filter(Contact._last_name.ilike(_contact_last_name)) \
                .join(dup_contacts, and_(Contact._last_name == dup_contacts._last_name)) \
                .all()