在 SQLAlchemy (Python) 中 UNION 查询列表的正确方法是什么?
What's the proper way to UNION a list of queries in SQLAlchemy (Python)?
所以我有一个 SQLAlchemy Query
对象的列表,我想 UNION 所有的对象。
例如,如果我的列表中有以下等价物:
SELECT id, name FROM person
SELECT id, name FROM employee
我会得到相当于:
(SELECT id, name FROM person)
UNION
(SELECT id, name FROM employee)
我不知道列表中有什么,列表可能包含许多 Query
对象,但当然我列表中每个 SQLAlchemy Query
对象的结果签名是 100% 相同的。
目前我是这样做 UNION 的:
if not q_list:
return []
big_q = q_list.pop(0)
if q_list:
big_q = big_q.union(*q_list)
result = [dict(row) for row in dbsession.execute(big_q)]
但是由于某些奇怪的原因,我没有得到与 运行 所有查询单独然后将结果连接在一起时相同的结果。我必须错误地做工会。那我该怎么做 UNION 呢?
我想你可能会期待 UNION ALL
。
来自postgresql documentation,第二部分..
UNION effectively appends the result of query2 to the result of query1
(although there is no guarantee that this is the order in which the
rows are actually returned).
Furthermore, it eliminates duplicate rows
from its result, in the same way as DISTINCT, unless UNION ALL is
used.
试试这个:
if q_list:
big_q = big_q.union_all(*q_list)
还有一个函数可以执行union all,比如:
q = union_all(*q_list)
我的问题与 union
调用无关。我对 UNION 的查询列表是使用一个函数创建的,该函数在每个对象上执行类似的操作:
sql.expression.bindparam(
"current_timestamp", value=start_timestamp
)
似乎因为我列表中的所有查询对象都具有相同的参数名称 (current_timestamp
),所以当使用 bindparam
时,它们都使用相同的值而不是各自的值。
我只需要使用 unique
参数来解决我的问题:
sql.expression.bindparam(
"current_timestamp", unique=True, value=start_timestamp
)
这样他们都能按预期获得 start_timestamp
值。
所以我有一个 SQLAlchemy Query
对象的列表,我想 UNION 所有的对象。
例如,如果我的列表中有以下等价物:
SELECT id, name FROM person
SELECT id, name FROM employee
我会得到相当于:
(SELECT id, name FROM person)
UNION
(SELECT id, name FROM employee)
我不知道列表中有什么,列表可能包含许多 Query
对象,但当然我列表中每个 SQLAlchemy Query
对象的结果签名是 100% 相同的。
目前我是这样做 UNION 的:
if not q_list:
return []
big_q = q_list.pop(0)
if q_list:
big_q = big_q.union(*q_list)
result = [dict(row) for row in dbsession.execute(big_q)]
但是由于某些奇怪的原因,我没有得到与 运行 所有查询单独然后将结果连接在一起时相同的结果。我必须错误地做工会。那我该怎么做 UNION 呢?
我想你可能会期待 UNION ALL
。
来自postgresql documentation,第二部分..
UNION effectively appends the result of query2 to the result of query1 (although there is no guarantee that this is the order in which the rows are actually returned).
Furthermore, it eliminates duplicate rows from its result, in the same way as DISTINCT, unless UNION ALL is used.
试试这个:
if q_list:
big_q = big_q.union_all(*q_list)
还有一个函数可以执行union all,比如:
q = union_all(*q_list)
我的问题与 union
调用无关。我对 UNION 的查询列表是使用一个函数创建的,该函数在每个对象上执行类似的操作:
sql.expression.bindparam(
"current_timestamp", value=start_timestamp
)
似乎因为我列表中的所有查询对象都具有相同的参数名称 (current_timestamp
),所以当使用 bindparam
时,它们都使用相同的值而不是各自的值。
我只需要使用 unique
参数来解决我的问题:
sql.expression.bindparam(
"current_timestamp", unique=True, value=start_timestamp
)
这样他们都能按预期获得 start_timestamp
值。