sqlalchemy:我如何在sqlalchemy中执行这个简单的子查询?

时间:2012-07-17 20:20:59

标签: sqlalchemy

两种型号:

class this(DeclarativeBase):

    __tablename__ = 'this'

    'Columns'
    id = Column(Integer, primary_key=True)

    'Relations'
    that = relation('that', foreign_keys=id, backref='this')

class that(DeclarativeBase):

    __tablename__ = 'that'

    'Columns'
    id = Column(Integer, primary_key=True)
    this_id = Column(Integer, ForeignKey('this.id'))

我想运行这个简单的SQL查询:

SELECT id, (SELECT COUNT(*) FROM that WHERE this_id = this1.id) AS thatcount FROM this AS this1

我可以通过以下方式在sqlalchemy中获得相同的结果:

results = session.query(model.this.id, 
                        func.count(model.that.id).label('thatcount')) \
                 .join(model.that) \
                 .group_by(model.this.id)

但是,结果SQL不是我想要的:

SELECT
this.id AS this_id,
count(that.id) AS thatcount 
FROM this
INNER JOIN that ON this.id = that.this_id
GROUP BY this.id

我在sqlalchemy中遗漏了几个基本想法...

1)如何在FROM子句中“标记”表格? 2)如何创建引用父查询结果的子查询?

希望这很简单,我只是不理解,因为我对sqlalchemy比较新...当然我可以运行原始SQL,但我对sqlalchemy印象深刻,我确信这是可能的。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

qry = select([
        this.id,
        select([func.count().label('xx')], this.id == that.this_id).as_scalar().label('thatcount'),
        ])

产生

SELECT this.id, (SELECT count(*) AS xx
FROM that
WHERE this.id = that.this_id) AS thatcount
FROM this

直接回答您的问题:

  1. 使用label()
  2. 您不需要,只需使用whereclause的{​​{1}}来指示主查询和子查询之间的连接条件。
  3. 请注意,我更喜欢selectfunc.count(that.id),因为它更明确。