用列值替换 LIMIT 静态值
Replacing LIMIT static value with column value
我有一个 table 看起来像这样:
ID Damage
1 10
2 7
3 153587
4 1
...1M more rows
我有另一个 table 有一个列代表我需要抓取的行数的百分位,所以如果它的前 10 个百分位列值将是 100000 我想根据损坏抓取.
有没有办法不用说 LIMIT 100000,因为百分位数发生变化,基本上用变量或列值替换 100000?
第二个table:
Days Percentile_Affected Damage_Sum
14 87000
30 161000
90 371000
...
如果id没有间隔,你可以直接使用id
。相反,您可以添加一个计数变量并使用它:
select t.*
from (select t.*, (@rn := @rn + 1) as rn
from (select t.*
from t
order by id
) t cross join
(select @rn := 0) params
) t
where rn < (select "a column" from "another table");
另一种方法是构造查询并使用动态 SQL:
select @sql := replace('select t.* from t limit [limit]', [limit], "a column")
from "another table";
prepare stmt from @sql;
execute stmt;
或者,为限制使用占位符:
set @sql = 'select t.* from t limit ?';
select @limit := "a column"
from "another table";
prepare stmt from @sql;
execute stmt using @limit;
我有一个 table 看起来像这样:
ID Damage
1 10
2 7
3 153587
4 1
...1M more rows
我有另一个 table 有一个列代表我需要抓取的行数的百分位,所以如果它的前 10 个百分位列值将是 100000 我想根据损坏抓取.
有没有办法不用说 LIMIT 100000,因为百分位数发生变化,基本上用变量或列值替换 100000?
第二个table:
Days Percentile_Affected Damage_Sum
14 87000
30 161000
90 371000
...
如果id没有间隔,你可以直接使用id
。相反,您可以添加一个计数变量并使用它:
select t.*
from (select t.*, (@rn := @rn + 1) as rn
from (select t.*
from t
order by id
) t cross join
(select @rn := 0) params
) t
where rn < (select "a column" from "another table");
另一种方法是构造查询并使用动态 SQL:
select @sql := replace('select t.* from t limit [limit]', [limit], "a column")
from "another table";
prepare stmt from @sql;
execute stmt;
或者,为限制使用占位符:
set @sql = 'select t.* from t limit ?';
select @limit := "a column"
from "another table";
prepare stmt from @sql;
execute stmt using @limit;