这是一个硬编码相等的视图:
create or replace view v1 as select * from mytable where x=3;
是否有可能创建一个“参数化”的等价物?
create or replace SOMETHING v2(value) as
select * from mytable where x=value;
首选标准 SQL,但欢迎使用 sqlite、postgresql 和 duckdb 特定答案。
Postgresql 版本
create or replace function v2(val int)
returns setof mytable language sql as $$
select *
from mytable
where x = val;
$$;
select * from v2(3);
这非常依赖于产品,但是对于 postgres 你可以使用函数,但是视图的工作方式相同,所以真的没有必要这样做
你也可以使用物化视图https://www.postgresql.org/docs/current/sql-creatematerializedview.html
CREATE tABLe mytable ( f1 int, f2 int, x int)
CREATE TABLE
CREATE FUNCTION v2(int) RETURNS TABLE(f1 int, f2 text)
AS $$ select f1,f2 from mytable where x=$1; $$
LANGUAGE SQL;
SELECT * FROM v2(42);
CREATE FUNCTION
f1 | f2 |
---|
SELECT 0
CREATE VIEW myview As select f1,f2,x from mytable
CREATE VIEW
SELECT f1,f2 FROM myview WHERE x = 42
f1 | f2 |
---|
SELECT 0