【发布时间】:2021-05-07 13:28:23
【问题描述】:
考虑以下数据库表:
ID ticker description
1 GDBR30 30YR
2 GDBR10 10YR
3 GDBR5 5YR
4 GDBR2 2YR
可以用这段代码复制:
from sqlalchemy import (
Column,
Integer,
MetaData,
String,
Table,
create_engine,
insert,
select,
)
engine = create_engine("sqlite+pysqlite:///:memory:", echo=True, future=True)
metadata = MetaData()
# Creating the table
tickers = Table(
"tickers",
metadata,
Column("id", Integer, primary_key=True, autoincrement=True),
Column("ticker", String, nullable=False),
Column("description", String(), nullable=False),
)
metadata.create_all(engine)
# Populating the table
with engine.connect() as conn:
result = conn.execute(
insert(tickers),
[
{"ticker": "GDBR30", "description": "30YR"},
{"ticker": "GDBR10", "description": "10YR"},
{"ticker": "GDBR5", "description": "5YR"},
{"ticker": "GDBR2", "description": "2YR"},
],
)
conn.commit()
我需要过滤 tickers 的一些值:
search_list = ["GDBR10", "GDBR5", "GDBR30"]
records = conn.execute(
select(tickers.c.description).where((tickers.c.ticker).in_(search_list))
)
print(records.fetchall())
# Result
# [('30YR',), ('10YR',), ('5YR',)]
但是,我需要以 search_list 的排序方式排序的结果元组列表。也就是说,我需要以下结果:
print(records.fetchall())
# Expected result
# [('10YR',), ('5YR',), ('30YR',)]
使用 SQLite,您可以创建一个包含两列(id 和 ticker)的 cte。应用以下代码将产生预期的结果(请参阅Maintain order when using SQLite WHERE-clause and IN operator)。不幸的是,我无法将 SQLite 解决方案转移到 sqlalchemy。
WITH cte(id, ticker) AS (VALUES (1, 'GDBR10'), (2, 'GDBR5'), (3, 'GDBR30'))
SELECT t.*
FROM tbl t INNER JOIN cte c
ON c.ticker = t.ticker
ORDER BY c.id
假设,我有search_list_tuple 如下,我想如何编码sqlalchemy 查询?
search_list_tuple = [(1, 'GDBR10'), (2, 'GDBR5'), (3, 'GDBR30')]
【问题讨论】:
-
这是一个工作示例 ;-)
标签: python sqlalchemy