将带有嵌套SELECT,EXIST,SELECT NEXT子句的mysql转换为python sqlalchemy语句

时间:2014-03-12 19:22:11

标签: python mysql sqlalchemy flask-sqlalchemy

所以我有这个陈述

SELECT h.usd FROM historic h, block b 
WHERE UNIX_TIMESTAMP(h.timestamp) <=b.block_nTime 
AND NOT EXISTS 
(SELECT 'NEXT' FROM 
historic h2 where h2.timestamp > h.timestamp 
AND UNIX_TIMESTAMP(h2.timestamp) <=b.block_nTime) AND b.block_id = 'id'

我正在尝试将其转换为python sqlalchemy语句 - 这就是我有多远。

from sqlalchemy import *
from sqlalchemy.sql import func
from sqlalchemy.orm import Session

#{...}

h = alias(historic)
h2 = alias(historic)

session.query(h.c.usd).filter(
and_(h.c.timestamp <= block.c.block_nTime,   
~exists(
func.next_value(Sequence(h2.c.timestamp))
).where(
and_(h2.c.timestamp > h.c.timestamp, h2.c.timestamp <= block.c.block_nTime
) & block.c.id == block_id)))

我也是如何得到这个错误的:

sqlalchemy.exc.ArgumentError: columns argument to select() must be a Python list or other iterable

认为我没有正确使用Sequence()。问题可能是什么?

提前致谢!

1 个答案:

答案 0 :(得分:1)

您获得的错误会引用exists。只需将参数包装在一个列表中就可以了:

Before: ~exists(func.next_value(Sequence(h2.c.timestamp)))
After: ~exists([func.next_value(Sequence(h2.c.timestamp))])