Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

Python sqlalchemy: group and order by after union of two tuples

I'm trying to group and order a union of two tuples in python using sqlalchemy,

My use-case is:

there are two tables, A & B Both table have two same field share_id and time.

q1 = AModel.query.with_entities(AModel.share_id.label('ID') , AModel.time.label('time')).filter_by(condition)
q2 = BModel.query.with_entities(BModel.share_id.label('ID') , BModel.time.label('time')).filter_by(condition)

result = q1.union(q2).group_by('ID').order_by(desc('time')).all()

I'm trying to get as result date with unique id and max time in relevant table. the order clause only applied to q1 data.

If q2 have duplicate entry with more recent time then The result object didn't represent what want to get from the query

Can some suggest me what to do in my use-case?

Thanks.

question from:https://stackoverflow.com/questions/65923819/python-sqlalchemy-group-and-order-by-after-union-of-two-tuples

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found a solution to workaround this issue.

q1 = AModel.query.with_entities(AModel.share_id.label('ID') , AModel.time.label('time')).filter_by(condition)
q2 = BModel.query.with_entities(BModel.share_id.label('ID') , BModel.time.label('time')).filter_by(condition)

unionSet = union(q1, q2).alias()
result = db.session.query(unionSet).with_entities(unionSet.c.ID, func.max(unionSet.c.time)) 
            .group_by(unionSet.c.document_id).order_by(func.max(unionSet.c.time).desc()).all()

This will return the expacted result from two table with same columns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...