所需的原始SQL:
SELECT
id
FROM
(SELECT some_table.id FROM some_table WHERE some_table.some_field IS NULL) AS subq1
UNION
(SELECT some_table.id WHERE some_table.some_field IS NOT NULL)
LIMIT 10;
下面是python代码:
import sqlalchemy
SOME_TABLE = sqlalchemy.Table(
'some_table',
sqlalchemy.MetaData(),
sqlalchemy.Column('id', sqlalchemy.Integer, primary_key=True),
sqlalchemy.Column('some_field', sqlalchemy.Text))
stmt_1 = sqlalchemy.sql.select(SOME_TABLE.columns).where(SOME_TABLE.columns.some_field != None)
stmt_2 = sqlalchemy.sql.select(SOME_TABLE.columns).where(SOME_TABLE.columns.some_field == None)
# This gets a programming error.
stmt_1.union(stmt_2).limit(10);
以下是出现此错误的输出SQL(已交换参数):错误:在“UNION”或其附近有语法错误:
SELECT some_table.id, some_table.some_field
FROM some_table
WHERE some_table.some_field IS NOT NULL
LIMIT 10 UNION SELECT some_table.id, some_table.some_field
FROM some_table
WHERE some_table.some_field IS NULL
LIMIT 10
LIMIT 10
如何为子查询设置别名?
1条答案
按热度按时间yhived7q1#
我用了一个稍微不同的方法:
下面是生成的SQL查询:
我想这就是你想要的结果。