SQLAlchemy 的 Query.distinct方法的行为不一致:
>>> [tag.name for tag in session.query(Tag).all()]
[u'Male', u'Male', u'Ninja', u'Pirate']
>>> session.query(Tag).distinct(Tag.name).count()
4
>>> session.query(Tag.name).distinct().count()
3
所以第二种形式给出了正确的结果,但第一种形式没有。这似乎发生在 SQLite 但不是 Postgres。我有一个函数,它传递了一个查询对象以对其应用 distinct
子句,因此使用上面的第二种方法重写所有内容将非常困难。我有什么明显的遗漏吗?
最佳答案
根据文档:
When present, the Postgresql dialect will render a DISTINCT ON (>) construct.
因此,将列表达式传递给 distinct()
仅适用于 PostgreSQL(因为存在 DISTINCT ON
)。
在表达式 session.query(Tag).distinct(Tag.name).count()
sqlalchemy 忽略 Tag.name
并产生查询(在所有字段):
SELECT DISTINCT tag.country_id AS tag_country_id, tag.name AS tag_name
FROM tag
正如你所说,在你的情况下 distinct(Tag.name)
被应用 - 所以不仅仅是 count()
考虑使用这个:
session.query(Tag).distinct(Tag.name).group_by(Tag.name).count()
希望对您有所帮助。
关于python - 使用 SQLite 在 SQLAlchemy 中返回不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17223174/