考虑一个如下所示的查询:
my $query=<<QUERY;
select * from foo1 where col < ?
union all
select * from foo2 where col < ?
QUERY
假设实际查询确实需要联合并且不能以另一种方式有效地解决。 where子句中的变量将始终相同。有什么方法可以构造这个,这样我只需要传递1个参数来执行而不是两次传递相同的参数?
答案 0 :(得分:4)
在“真实”数据库中,您可以参数化查询并将查询作为参数传递。这是另一种解决方案:
with const as (select ? as val)
select *
from ((select foo1.*
from foo1 cross join const
where col < const.val
) union all
(select foo2.*
from foo2 cross join const
where col < const.val
)) t
我并不是说这是一个好主意。但是,我有时发现将参数收集到这样的子查询中然后在需要的地方加入它们非常有用。
答案 1 :(得分:4)
您可以使用列表重复运算符。
$sth->execute(($value) x 2);
答案 2 :(得分:3)
可以尝试以下方法,我假设您将整数传递给where子句...
DECLARE @variableName as int
SET @variableName = ? --the value gets passed here once
select * from foo1 where col < @variableName -- and gets used here
union all
select * from foo2 where col < @variableName -- and here!