2014-02-28 5 views
0

내 SQL 쿼리에서 동적으로 제한을 설정하고 싶습니다. 매개 변수 테이블에 한계를 설정하고 싶습니다.mysql 제한 하위 쿼리

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

어떻게 구현합니까? 도와주세요

답변

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; 
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)