SQL - 具有内部IF或CASE的SELECT

时间:2016-04-01 23:26:39

标签: sql postgresql if-statement select

尝试有一行显示' YES'或者' NO'取决于找到的值(如果在参数中给出的日期之前已经处理了树,则说“是”否则)。

这是我的功能:

CREATE OR REPLACE FUNCTION tree_care(care_date DATE)
RETURNS TABLE(name VARCHAR(32), type VARCHAR(32), treated TEXT) AS
$$
BEGIN
RETURN QUERY
SELECT tree.name,
       tree.type,
       IF EXISTS (SELECT * FROM treatment
                  JOIN tree ON tree.name = treatment.tree_name
                  WHERE treatment.date < care_date) THEN
            'YES'::text
       ELSE
            'NO'::text
       END IF
FROM tree;
END;
$$

我收到以下错误:

ERROR:  syntax error at or near "EXISTS"
LINE 8:            IF EXISTS (SELECT * FROM treatment

如何在SELECT中实现IF语句?

PS:使用postgresql 9.4

1 个答案:

答案 0 :(得分:0)

IF是控制流程。使用CASE,因为这是在SELECT声明中:

SELECT tree.name,
       tree.type,
       (CASE WHEN EXISTS (SELECT 1
                          FROM treatment
                          WHERE tree.name = treatment.tree_name AND
                                treatment.date < care_date
                         ) THEN
             THEN 'YES'::text
             ELSE 'NO'::text
        END) as Flag
FROM tree;

我也猜测你想要一个相关的子查询,而不是一个独立的子查询。