Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy: distinct only on one column

My table looks like this:

    title      |    slug
------------------------------
The Title      | the-title
Another Title  | another-title
another title  | another-title

I want to select by distinct slug, but also want the title returned as part of the results. Which title gets returned for multiple matches, I don't care.

So my results look like this:

[('The Title', 'the-title'), ('Another Title', 'another-title')]
like image 854
priestc Avatar asked Jun 21 '26 02:06

priestc


2 Answers

You probably want to do something like:

session.query(func.max(Table.title), Table.slug).group_by(Table.slug).all()
like image 70
Derek Litz Avatar answered Jun 22 '26 15:06

Derek Litz


You can also solve this with:

session.query(Table.title, Table.slug).distinct(Table.slug)

This also allows you to return additional fields (say you wanted to see Table.id) in the same .query() field list, without requiring a separate subquery.

like image 41
shroud Avatar answered Jun 22 '26 16:06

shroud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!