简体   繁体   English

SQLAlchemy从子查询中选择并按子查询字段排序

[英]SQLAlchemy select from subquery and order by subquery field

I have a database table with tweets in a jsonb field. 我有一个在jsonb字段中带有推文的数据库表。 I have a query to get the tweets ordered by the most retweeted, this is what it looks like: 我有一个查询,以查询转发次数最多的推文,这是这样的:

SELECT * FROM (
   SELECT DISTINCT ON (raw->'retweeted_status'->'id_str')
     raw->'retweeted_status' as status,
     raw->'retweeted_status'->'retweet_count' as cnt
   FROM tweet
   WHERE (raw->'retweeted_status') is not null
   ORDER BY raw->'retweeted_status'->'id_str', cnt DESC
) t
ORDER BY cnt DESC

I'm trying to create this query with sqlalchemy, this is where i got so far: 我正在尝试使用sqlalchemy创建此查询,这是到目前为止我到达的地方:

session.query(Tweet.raw['retweeted_status'], 
         Tweet.raw['retweeted_status']['retweet_count'].label('cnt'))\
        .filter(~Tweet.raw.has_key('retweeted_status'))\
        .distinct(Tweet.raw['retweeted_status']['id_str']).order_by(Tweet.raw['retweeted_status']['id_str'].desc()).subquery()

But how to go from that to order by cnt? 但是如何从cnt到order?

It may not produce the exact query you have shown but should point you in the right direction: you can use your label 'cnt' in order_by , like: .order_by('cnt') . 它可能不会产生您所显示的确切查询,但应该为您指明正确的方向:您可以在order_by使用标签'cnt' ,例如: .order_by('cnt')

Moreover you can use your label as an argument for sqlalchemy.desc function. 此外,您可以将标签用作sqlalchemy.desc函数的参数。 Summing up: 加起来:

from sqlalchemy import desc

q = (
    session.query(
        Tweet.raw['retweeted_status'],
        Tweet.raw['retweeted_status']['retweet_count'].label('cnt')
    )
    .filter(~Tweet.raw.has_key('retweeted_status'))
    .distinct(
        Tweet.raw['retweeted_status']['id_str']
    )
    .order_by(desc('cnt'))
).subquery()

Additional hint: you can format your query nicely if you put it in parentheses. 附加提示:如果将查询放在括号中,则可以很好地格式化查询。

You may want to read answers to a general question on python sqlalchemy label usage too. 您可能也想阅读有关python sqlalchemy标签用法的一般问题的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM