<p>我正在尝试实现一个带有嵌套select子句的select,以查找没有任何子级的父级。我的表格(完全简化)如下:</p>
<pre><code>class Person(Base):
__tablename__ = "person"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=True, default=None)
class ChildTable(Base):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
data = Column(String)
person_id = Column(Integer, ForeignKey("person.id"), nullable=True)
</code></pre>
<p>在sql中,我的查询是</p>
<pre><code>select id from person where id not in (select person_id from foo);
</code></pre>
<p>如何在Python和sqlalchemy中实现这一点?我找到了这个<a href="https://stackoverflow.com/questions/20060485/sqlalchemy-select-using-reverse-inclusive-not-in-list-of-child-column-values">sqlalchemy, select using reverse-inclusive (not in) list of child column values</a>,但它依赖于声明的关系。我不使用关系,因为我有很多问题,主要是其他线程过期或更改其他线程缓存的数据,以及foo.person_id可以为空且不引用任何内容。</p>
<p>我该怎么做?我尝试了in}和任何运算符的组合,但抛出了不同的异常。例如,此尝试:</p>
<pre><code>empty_persons = config.Session.query(Person).filter(Person.id.notin_(ChildTable.\
person_id)).all()
</code></pre>
<p>这将失败:in()接受表达式列表或可选表达式。</p>
<p>这可能是一件简单的事情,但我不明白该怎么做。</p>
<p>右</p>