Python sqlalchemy中order by中的子查询
我需要一些sqlalchemy查询方面的帮助。 在sqlalchemy中实现这个mysql查询时遇到问题 MySQL查询:Python sqlalchemy中order by中的子查询,python,sqlalchemy,subquery,flask-sqlalchemy,Python,Sqlalchemy,Subquery,Flask Sqlalchemy,我需要一些sqlalchemy查询方面的帮助。 在sqlalchemy中实现这个mysql查询时遇到问题 MySQL查询: select u.post_id from user_record_cards u where u.record_card_id = 1 and u.count = 1 order by (select count(*) from post_likes p where p.post = u.p
select u.post_id
from
user_record_cards u
where
u.record_card_id = 1 and u.count = 1
order by (select
count(*)
from
post_likes p
where
p.post = u.post_id)
我的sqlalchemy查询是:
obj = (
UserRecordCard.query
.filter(
UserRecordCard.record_card_id == 1,
UserRecordCard.count == 1
).order_by(
Like.query.filter(
Like.post == UserRecordCard.post_id
).count()
).all()
)
我的回溯是:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/elements.py", line 3453, in _literal_as_text
"SQL expression object or string expected."
ArgumentError: SQL expression object or string expected.
您的问题是.count返回int或long,而不是子查询
为了做你打算做的事情,你必须这样做
from sqlalchemy import select, func
obj = (
UserRecordCard.query
.filter(
UserRecordCard.record_card_id == 1,
UserRecordCard.count == 1
)
.order_by(
select([
func.count()
])
.select_from(Like.__table__)
.where(Like.post == UserRecordCard.post_id)
.correlate(UserRecordCard.__table__)
)
)
correlate调用告诉SQLAlchemy不要尝试将UserRecordCard放入子select的from子句中,而是从周围的select中获取它
我不记得了,在子查询中可能需要也可能不需要使用别名或标量。但总体思路应该是正确的。-您需要什么帮助?显示代码、您得到的输出和您想要的输出。@Prune现在我添加了我的sqlalchemy和traceback!,希望有帮助!我们正在到达那里;那么,问题出在哪一行代码上?您曾尝试过哪些方法来简化代码,以将问题点与好的部分分开?我不熟悉SQLalchemy中的差异,所以我必须引导您,而不是自己解决它。问题是按子查询顺序排列。order\u byLike.query.filterLike.post==UserRecordCard.post\u id.count,如果您知道如何在SQLalchemy中实现子查询,我将不胜感激,我在google上找不到任何与此相关的好链接!谢谢你,伙计!。。这正是我想要的,它很有魅力!