在sqlalchemy中,我尝试联合表格,然后使用WHERE
和ORDER_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 ...
SQLAlchemy的:
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]
感谢任何帮助
答案 0 :(得分:2)
你错误地使用了第二个参数“select()”,这实际上是“whereclause”(虽然我们鼓励这些天使用where()
方法)。 FROM子句通常隐含在您选择的列中。对于“select *”,我们可以使用select_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