0
我想動態地在我的sql查詢中設置限制。我想在參數表中設置限制。mysql限制子查詢
select col1, col2, col3
from table
where col4 = 'abc'
limit (select a from param)
如何做到這一點?請幫助
我想動態地在我的sql查詢中設置限制。我想在參數表中設置限制。mysql限制子查詢
select col1, col2, col3
from table
where col4 = 'abc'
limit (select a from param)
如何做到這一點?請幫助
您不能使用參數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;
您可以使用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)