gpt4 book ai didi

sqlalchemy - SQLAlchemy 中的别名联合

转载 作者:行者123 更新时间:2023-12-05 04:18:25 32 4
gpt4 key购买 nike

在 sqlalchemy 中,我试图合并表,然后使用 WHEREORDER_BY 创建别名

有点像

SELECT *
FROM (
SELECT [TABLE_ONE].[SOME_ID] AS [SOME_ID]
FROM [TABLE_ONE]
UNION
SELECT [TABLE_TWO].[SOME_ID] AS [SOME_ID]
FROM [TABLE_TWO]
) AS anon_1
WHERE ...

SQL炼金术:

select_q = select([TABLE_ONE.c.SOME_ID], TABLE_ONE)
select_w = select([TABLE_TWO.c.SOME_ID], TABLE_TWO)
union_qw = union(select_q,select_w)
union_qw_aliased = aliased(union_qw)
s = select('*',union_qw_aliased)

但 SQLAlchemy 生成 SQL 代码:

SELECT anon_1.[SOME_ID]
FROM (SELECT [TABLE_ONE].[SOME_ID] AS [SOME_ID]
FROM [TABLE_ONE] UNION SELECT [TABLE_TWO].[SOME_ID] AS [SOME_ID]
FROM [TABLE_TWO]) AS anon_1
WHERE SELECT [TABLE_ONE].[SOME_ID]
FROM [TABLE_ONE] UNION SELECT [TABLE_TWO].[SOME_ID]
FROM [TABLE_TWO]

感谢任何帮助

最佳答案

您错误地使用了“select()”的第二个参数,这实际上是“whereclause”(尽管现在我们鼓励使用 where() 方法)。 FROM 子句通常隐含在您选择的列中。对于您的“select *”,我们可以使用 select_from() 设置显式 FROM:

from sqlalchemy import *

m = MetaData()
t1 = Table('t1', m, Column('id', Integer))
t2 = Table('t2', m, Column('id', Integer))

select_q = select([t1])
select_w = select([t2])
union_qw = union(select_q, select_w)
union_qw_aliased = union_qw.alias()
s = select('*').select_from(union_qw_aliased)

print s

输出:

SELECT * 
FROM (SELECT t1.id AS id
FROM t1 UNION SELECT t2.id AS id
FROM t2) AS anon_1

要在 WHERE 上执行更多操作,请使用 where() 添加并针对 union_qw_aliased 执行此操作:

print s.where(union_qw_aliased.c.id == 5)

输出:

SELECT * 
FROM (SELECT t1.id AS id
FROM t1 UNION SELECT t2.id AS id
FROM t2) AS anon_1
WHERE anon_1.id = :id_1

关于sqlalchemy - SQLAlchemy 中的别名联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15331055/

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