python - 在 sqlalchemy 中加入值

标签 python postgresql sqlalchemy

我想在 SQLalchemy 中运行以下 postgreSQL 查询:

select c.*
from comments c
join (
  values
    (1,1),
    (3,2),
    (2,3),
    (4,4)
) as x (id, ordering) on c.id = x.id
order by x.ordering

是否可以加入列表列表或元组列表之类的东西,并使用它们在 SQLalchemy 中提供排序?

最佳答案

from sqlalchemy import *

from yourdbmodule import dbsession


VALUES = ((1, 1), (3, 2), (2, 3), (4, 4))


temp_table = Table(
    'temp_table', MetaData(),
    Column('id', INT, primary_key=True),
    Column('ordering', INT),
    prefixes=['TEMPORARY']
)
temp_table.create(bind=dbsession.bind, checkfirst=True)


dbsession.execute(temp_table.insert().values(VALUES))


# Now you can query it
dbsession.query(Comments)\
    .join(temp_table, Comments.id == temp_table.c.id)\
    .order_by(temp_table.c.ordering)\
    .all()

关于python - 在 sqlalchemy 中加入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39036221/

相关文章:

python - 设置向后子字符串结尾的变量不能是数字吗?

python - 我如何在python中控制for循环的迭代

python - GCS 实体的 blob_key 以后可以安全使用吗?

sql - 如何在 Postgresql 中使用 ALTER 将 VARCHAR 类型更改为 DATETIME?

database - 具有静态加密和审计功能的开源数据库

sqlalchemy - 简单地格式化 FastApi 端点返回的 SQLAlchemy 模型

python - 从另一个 Cloud 项目调用 Firestore 数据库显示 "Permission Error"

sql - 将 NULL 值排序到表的末尾

python - SQLAlchemy 查询如何使用 MySQL 的 REGEXP 运算符?

python - 使用 INTERSECT 和 UNNEST 的 sqlalchemy