gpt4 book ai didi

python - SQLAlchemy、PostgreSQL 和 array_agg : How to select items from array_agg?

转载 作者:太空狗 更新时间:2023-10-29 20:51:53 26 4
gpt4 key购买 nike

我想使用 array_agg在子查询中,然后在我的主查询中通过它的数组索引使用聚合数据,但是,在尝试了许多不同的方法之后,我真的不知道应该怎么做;有人可以解释为什么在下面的示例中我得到了一系列 None 值而不是数组中的第一个类别吗?

我知道下面的简化示例可以在不对数组 [i] 执行 SELECT 的情况下完成,但它将解释问题的性质:

from sqlalchemy import Integer
from sqlalchemy.dialects.postgres import ARRAY

prods = (
session.query(
Product.id.label('id'),
func.array_agg(ProductCategory.id, type_=ARRAY(Integer)).label('cats'))
.outerjoin(
ProductCategory,
ProductCategory.product_id == Product.id)
.group_by(Product.id).subquery()
)

# Confirm that there's categories:
[x for x in session.query(prods) if len(x[1]) > 1][:10]
"""
Out[48]:
[(2428, [1633667, 1633665, 1633666]),
(2462, [1162046, 1162043, 2543783, 1162045]),
(2573, [1633697, 1633696]),
(2598, [2546824, 922288, 922289]),
(2645, [2544843, 338411]),
(2660, [1633713, 1633714, 1633712, 1633711]),
(2686, [2547480, 466995, 466996]),
(2748, [2546706, 2879]),
(2785, [467074, 467073, 2545804]),
(2806, [2545326, 686295, 686298, 686297])]
"""

# Ok now try to query to get the first category of each array:
[x for x in session.query(prods.c.cats[0].label('first_cat'))]

"""
(None),
(None),
(None),
(None),
(None),
(None),
(None),
(None),
(None),
(None),
(None),
"""

最佳答案

您可能做对了所有事情,但首先获取空数组。在您之前的查询中,您使用了 in-python 过滤 (len(x[1]) > 1)。您可以在执行之前打印 Query 表达式以确保。

您可能应该为您的基本查询添加一个 having 子句:

from sqlalchemy import Integer
from sqlalchemy.dialects.postgresql import ARRAY

cats_agg = func.array_agg(ProductCategory.id, type_=ARRAY(Integer)).label('cats')
prods = (
session.query(
Product.id.label('id'),
cats_agg,
.outerjoin(
ProductCategory,
ProductCategory.product_id == Product.id)
.group_by(Product.id)
.having(func.array_length(cats_agg, 1) > 1)
.subquery()
)

那么你也不需要 in-python 过滤。

关于python - SQLAlchemy、PostgreSQL 和 array_agg : How to select items from array_agg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23261944/

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