【问题标题】:SQL subquery using ORDER BY and LIMIT in SQLAlchemy在 SQLAlchemy 中使用 ORDER BY 和 LIMIT 的 SQL 子查询
【发布时间】:2014-10-08 03:25:52
【问题描述】:

我需要用 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。

提前致谢

【问题讨论】:

    标签: python mysql sql sqlalchemy flask-sqlalchemy


    【解决方案1】:

    您必须将这些子选择放入另一个子选择中才能获得派生表。否则子查询中的 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
      ) 
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      相关资源
      最近更新 更多