我正在尝试创建一个查询,其中我基于4个值搜索1个表。这些值都不是必需的,它应该基于所有这些值返回。
如果始终提供所有值,下面是我的处理方法。
CREATE OR REPLACE FUNCTION "GetValues"(
"@value1" TEXT,
"@value2" TEXT,
"@value3" TEXT
"@value4" TEXT
)
RETURNS TABLE(
"id" UUID,
"@value1" TEXT,
"@value2" TEXT,
"@value3" TEXT
"@value4" TEXT
) AS
$func$
BEGIN
RETURN QUERY SELECT
c."id",
c."value1",
c."value2",
c."value3",
c."value4"
FROM "values" AS v
WHERE "value1" = "@value1"
AND "value2" = "@value2"
AND "value3" = "@value3"
AND "value4" = "@value4";
END;
$func$ LANGUAGE PLPGSQL;
以下是我的想象,但我无法在其中进行任何操作。
IF ("@value1" IS NOT NULL) THEN
WHERE "value1" = "@value1"
END IF;
我应该做很多单独的选择,然后将它们全部与UNION结合吗?我认为这行不通,因为我只想显示符合所有条件的内容?
答案 0 :(得分:2)
使用Google Cloud Function trigger
SELECT
"id",
"value1",
"value2",
"value3",
"value4"
FROM "values"
WHERE "value1" = COALESCE("@value1", "value1")
AND "value2" = COALESCE("@value2", "value2")
AND "value3" = COALESCE("@value3", "value3")
AND "value4" = COALESCE("@value4", "value4")
无关但重要。在双引号中使用表名或列名肯定会不会,使生活更加轻松。表的名称“值”可能被认为是不良做法。