【问题标题】:mysql limit sub querymysql限制子查询
【发布时间】:2014-02-28 12:41:45
【问题描述】:

我想在我的 sql 查询中动态设置限制。我想在参数表中设置限制。

select col1, col2, col3 
from table 
where col4 = 'abc' 
limit (select a from param)

如何做到这一点?请帮忙

【问题讨论】:

    标签: mysql subquery limit


    【解决方案1】:

    您可以使用PREPARED STATEMENTS

    mysql> select * from t;
    +----+
    | id |
    +----+
    |  1 |
    |  2 |
    |  3 |
    |  4 |
    |  5 |
    +----+
    5 rows in set (0.00 sec)
    
    mysql> prepare stmt from 'select * from t limit ?';
    Query OK, 0 rows affected (0.01 sec)
    Statement prepared
    
    mysql> set @v = 2;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> execute stmt using @v;
    +----+
    | id |
    +----+
    |  1 |
    |  2 |
    +----+
    2 rows in set (0.00 sec)
    
    mysql> deallocate prepare stmt;
    Query OK, 0 rows affected (0.00 sec)
    

    【讨论】:

      【解决方案2】:

      您不能为limit 使用参数(除非您有准备好的语句)。您可以使用变量来枚举行:

      select col1, col2, col3
      from (select t.*, (@rn := @rn + 1) as rn
            from table cross join
                 (select @rn := 0) const
           ) t
      where rn <= PARAMETERVALUE;
      

      虽然我为此使用了子查询,但我认为您也可以这样做:

      select col1, col2, col3
      from table t cross join
           (select @rn := 0) const
      where (@rn := @rn + 1) <= PARAMETERVALUE;
      

      【讨论】:

        猜你喜欢
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-31
        • 2020-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多