在SQLAlchemy中使用ORDER BY和LIMIT的SQL子查询

时间:2014-08-14 13:01:55

标签: python mysql sql sqlalchemy flask-sqlalchemy

我需要用SQLAlchemy语言编写这个查询。

SELECT * FROM Servers where Servers.protocol='TCP' and (
1=(SELECT status FROM Status WHERE Servers_ip = Servers.ip AND Servers_port = Servers.port ORDER BY timestamp desc LIMIT 1) OR 
4=(SELECT status FROM Status WHERE Servers_ip = Servers.ip AND Servers_port = Servers.port ORDER BY timestamp desc LIMIT 1)
)

我有一个类Servers和一个具有表属性的类Status。

提前致谢

1 个答案:

答案 0 :(得分:0)

您必须将这些子选择放入另一个子集以获取派生表。否则子查询中的LIMIT将无效。应该这样做:

SELECT 
    * 
FROM 
    Servers 
where Servers.protocol='TCP' and (
1=(
    SELECT s.status FROM (
        SELECT status 
        FROM Status 
        WHERE Servers_ip = Servers.ip AND Servers_port = Servers.port 
        ORDER BY timestamp desc 
        LIMIT 1
    ) s 
  ) 
OR 
4=(
    SELECT t.status FROM (
        SELECT status 
        FROM Status 
        WHERE Servers_ip = Servers.ip AND Servers_port = Servers.port 
        ORDER BY timestamp desc 
        LIMIT 1
    ) t
  ) 
);