次のようなクエリを考えてみましょう。
my $query=<<QUERY;
select * from foo1 where col < ?
union all
select * from foo2 where col < ?
QUERY
実際のクエリには実際に結合が必要であり、別の方法で効率的に解決することはできないと想定します。where句の変数は常に同じになります。同じ引数を2回渡すのではなく、実行するために1つの引数を渡すだけでよいようにこれを構造化する方法はありますか?
次のことを試してみてください。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!
「実際の」データベースでは、クエリをパラメータ化して、引数としてクエリを渡すことができます。別の解決策は次のとおりです。
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
これが必ずしも良い考えだと言っているのではありません。ただし、このようなサブクエリにパラメータを収集し、必要に応じてそれらを結合すると非常に便利な場合があります。
リスト繰り返し演算子を使用できます。
$sth->execute(($value) x 2);