I am trying to write a query to get N last comments for several items.
I am currently looking at elements with an element request:
for i in itemIds:
Comment.query.filter_by(itemId=i).order_by(Comment.id.desc()).limit(3)
But it is very slow.
I would like to have one request that receives all the comments but does not know how to do this. I tried to use union, but did not get it to work. I see that there are problems with MySQL, order_byand union. I'm trying to do something:
a = Comment.query.filter_by(itemId=1).order_by(Comment.id.desc()).limit(3)
b = Comment.query.filter_by(itemId=2).order_by(Comment.id.desc()).limit(3)
u = union_all(a,b)
DB.session.query(Comment).select_from(u).all()
But that does not work. He complains about "Misuse of UNION and ORDER BY."
I am not a MySQL or SQLAlchemy ninja, and have been banging my head about it for hours.
Help me please! Any pointers or tips would be greatly appreciated.