【发布时间】:2014-02-28 12:41:45
【问题描述】:
我想在我的 sql 查询中动态设置限制。我想在参数表中设置限制。
select col1, col2, col3
from table
where col4 = 'abc'
limit (select a from param)
如何做到这一点?请帮忙
【问题讨论】:
我想在我的 sql 查询中动态设置限制。我想在参数表中设置限制。
select col1, col2, col3
from table
where col4 = 'abc'
limit (select a from param)
如何做到这一点?请帮忙
【问题讨论】:
您可以使用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)
【讨论】:
您不能为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;
【讨论】: