mysql限制子查询

时间:2014-02-28 12:41:45

标签: mysql subquery limit

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

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

如何实现这一目标?请帮忙

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您不能使用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;