我的所有SQLAlchemy模型查询都很好,但有一个给我提供了:
more than one row returned by a subquery used as an expression这是由SQLAlchemy生成的(缩写) SQL:
SELECT poi.key
,poi.pok
,poi.noc
,coalesce((
SELECT CASE
WHEN (sum(item.noc) IS NULL)
THEN NULL
ELSE :param_1
END AS anon_1
FROM item,poi
WHERE poi.key = item.poi_key
GROUP BY item.key
), poi.noc) AS coalesce_1
,coalesce((
SELECT sum(soi.noc) AS sum_1
FROM soi
WHERE soi.poi_key = poi.key
AND soi.is_shipped = 0
), :param_2) AS coalesce_2
,coalesce((
SELECT CASE
WHEN (sum(item.noc) IS NULL)
THEN NULL
ELSE :param_1
END AS anon_1
FROM item,poi
WHERE poi.key = item.poi_key
GROUP BY item.key
), poi.noc) - ee((
SELECT sum(soi.noc) AS sum_1
FROM soi
WHERE soi.poi_key = poi.key
AND soi.is_shipped = 0
), :param_2) AS anon_2
FROM poi模型是:
class POI(Base):
key = Column(Integer, primary_key=True)
pok = Column(Integer, nullable=False)
noc = Column(Integer, nullable=False)
__table_args__ = (UniqueConstraint(pok,),
ForeignKeyConstraint([pok],),{})我使用scoped_session是因为我的应用程序是多线程的,我认为这可能是问题所在。但事实并非如此。我尝试了使用Session的所有变体,但问题仍然存在。奇怪的是,在应用程序初始化时,当启动从数据库获取数据的多个线程时,只有这个查询会抛出错误。在某种程度上,只调用这个查询(手动)工作得很好。所以问题显然是在与其他查询的交互中。
这个错误对我来说有点模糊,但我认为问题是一个子查询应该返回一个结果,而不是许多结果。我不知道从哪里开始寻找答案。这是线程问题吗?会话问题?还有别的吗?
发布于 2016-02-07 07:44:15
我相信你不需要在2个子查询中使用FROM item,poi,我也删除了其中的group by。回归涉及:param_1的case表达式我不确定我下面的建议是否正确,但您需要先创建一个SUM()值,然后才能测试该SUM()是否为空。
SELECT
poi.key
, poi.pok
, poi.noc
, COALESCE((
SELECT SUM(COALESCE(item.noc,:param_1))
FROM item
WHERE poi.key = item.poi_key
)
, poi.noc) AS coalesce_1
, COALESCE((
SELECT
SUM(soi.noc) AS sum_1
FROM soi
WHERE soi.poi_key = poi.key
AND soi.is_shipped = 0
)
, @param_2) AS coalesce_2
, COALESCE((
SELECT SUM(COALESCE(item.noc,:param_1))
FROM item
WHERE poi.key = item.poi_key
)
, poi.noc) - ee((
SELECT
SUM(soi.noc) AS sum_1
FROM soi
WHERE soi.poi_key = poi.key
AND soi.is_shipped = 0
)
, :param_2) AS anon_2
FROM poihttps://stackoverflow.com/questions/35247731
复制相似问题