gpt4 book ai didi

python - SQLAlchemy子查询,它们适用于这种情况吗

转载 作者:行者123 更新时间:2023-11-29 21:00:39 25 4
gpt4 key购买 nike

我已经阅读了很多有关 SQLAlchemy 子查询的内容,并且我认为它以某种方式适用于我的问题。

我有以下两个疑问

Query 1=>isp_ratings_per_service = db.session.query(func.count(Ratings.ratings_value).label('count_of_users'),
func.sum(Ratings.ratings_value).label('sum_of_ratings'),
func.avg(Ratings.ratings_value).label('avg_of_ratings'),
Isps.isp_name, Service_metric.metric_name, Services.service_name) \
.filter(Service_metric_ratings.isp_id == Isps.isp_id) \
.filter(Service_metric_ratings.ratings_value == Ratings.ratings_value) \
.filter(Service_metric_ratings.metric_id == Service_metric.metric_id) \
.filter(Service_metric_ratings.user_id == User.user_id) \
.filter(Service_metric_ratings.service_id == Services.service_id) \
.filter(Service_metric.metric_name == metric_name) \
.filter(Services.service_name == service_name) \
.group_by(Isps.isp_name)

Query 2 => ratings_table_values = db.session.query(Ratings.rating_value, Ratings.rating_comment)

我想使用此行中存储的值

func.avg(Service_metric_ratings.ratings_id).label('avg_of_ratings'),

根据此值选择另一个表中的数据,如下所示

for i in isp_ratings_per_service:
(round(i.avg_of_ratings)))
ratings_table_values = Ratings.query.filter_by(rating_value=(round(i.avg_of_ratings)))

是否可以使用子查询将它们放入一个查询中,目前的问题是它在 flask 模板中创建了 2 次迭代,这没有给我想要的结果,如下所示

 {% for i in ratings_table_values %}
<tr>
<td>{{ i.rating_value}}</td>
<td>{{ i.rating_comment}}</td>
{% endfor %}

{% for i in isp_ratings_per_service %}
blah blah blah
{% endfor %}

我希望一个查询能够给出我想要的结果,

最佳答案

我设法像这样解决我自己的问题,查询是分开的,不需要连接并且它工作完美。我在 Jinja 中发展了我的逻辑

{% for i in isp_ratings_per_service %}
<td>{{ i.isp_name }}</td>
<td>{{ i.metric_name }}</td>
<td>{{ i.service_name }}</td>
<td>{{ i.count_of_users }}</td>
<td>{{ i.sum_of_ratings }}</td>
<td>{{ i.avg_of_ratings|round|int }}</td>
{% for m in ratings_table_values %}
{% if (m.ratings_value) ==(i.avg_of_ratings|round|int)%}
<td>{{ m.ratings_comment}}</td>
{% endif %}
{% endfor %}
</tr>
{% else %}
<tr><td colspan="7"><em>No entries here so far</em></td></tr>
{% endfor %}

关于python - SQLAlchemy子查询,它们适用于这种情况吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37255130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com