如何在sqlalchemy中加入临时表

时间:2015-08-18 13:12:37

标签: python sql postgresql sqlalchemy

最初的问题是使用给定的ID列表以相同的顺序从DB检索文档。使用原始SQL我可以这样做

select c.id, c.ctime
from clusters c 
join (
   values 
      (910453, 5),
      (910483, 2),
      (910496, 1),
      (910503, 4),
      (910508, 3)
) as x (id, ordering) on c.id = x.id
order by x.ordering

使用sqlalchemy有没有办法做到这一点?此外,结果类型的数据应该是sqlalchemy QuerySet,所以我不能使用python的排序

1 个答案:

答案 0 :(得分:0)

使用以下查询: -

select c.id, c.ctime
from clusters c 
join (
      SELECT (910453 AS id, 5 AS ordering) UNION ALL
      SELECT (910483, 2) UNION ALL
      SELECT (910496, 1) UNION ALL
      SEELCT (910503, 4) UNION ALL
      SELECT (910508, 3)
     ) as x on c.id = x.id
order by x.ordering