在 SQLAlchemy/Elixir 中选择不同的列值 [英] Selecting distinct column values in SQLAlchemy/Elixir
问题描述
在我使用 SQLAlchemy 和 Elixir 编写的一个小脚本中,我需要获取特定列的所有不同值.在普通的 SQL 中,这很简单
In a little script I'm writing using SQLAlchemy and Elixir, I need to get all the distinct values for a particular column. In ordinary SQL it'd be a simple matter of
SELECT DISTINCT `column` FROM `table`;
而且我知道我可以手动"运行该查询,但如果可以的话,我宁愿坚持使用 SQLAlchemy 声明式语法(和/或 Elixir).我确信这一定是可能的,我什至在 SQLAlchemy 文档中看到了对这类事情的暗示,但是我已经花了几个小时(以及 Elixir 的文档)来搜索该文档,但我不能似乎真的想知道如何做到这一点.那么我错过了什么?
and I know I could just run that query "manually," but I'd rather stick to the SQLAlchemy declarative syntax (and/or Elixir) if I can. I'm sure it must be possible, I've even seen allusions to this sort of thing in the SQLAlchemy documentation, but I've been hunting through that documentation for hours (as well as that of Elixir) and I just can't seem to actually figure out how it would be done. So what am I missing?
推荐答案
可以查询映射类的列属性,Query类有一个生成的distinct()
方法:
You can query column properties of mapped classes and the Query class has a generative distinct()
method:
for value in Session.query(Table.column).distinct():
pass
这篇关于在 SQLAlchemy/Elixir 中选择不同的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!