Select 1 到变量 postgresql?

Select 1 into variable postgresql?

我在触发器过程中有这个 select 语句:

  SELECT 1 FROM some_table WHERE "user_id" = new."user_id"
  AND created >= now()::date;

如何将结果存储在变量中并在 IF 语句中重用它:

IF NOT EXISTS (var_name) THEN ...;

程序(现在我在 IF 语句中有 select,但我想要单独的)

CREATE OR REPLACE FUNCTION add_row() RETURNS TRIGGER AS $$
  BEGIN
    //need to check if row was created around today
    IF NOT EXISTS (SELECT 1 FROM some_table WHERE "user_id" = new."user_id"
  AND created >= now()::date) THEN
      INSERT INTO another_table VALUES(1, 2, 3);
    END IF;
  END;
$$ LANGUAGE plpgsql;

要将查询结果存储到变量中,您需要声明一个变量。然后就可以用select .. into ..store the result了。但我会为此目的使用 boolean 和存在条件。

CREATE OR REPLACE FUNCTION add_row() 
  RETURNS TRIGGER 
AS $$
declare
  l_row_exists boolean;
BEGIN
  select exists (SELECT *
                 FROM some_table 
                 WHERE user_id = new.user_id
                  AND created >= current_date)
    into l_row_exists;

  IF NOT l_row_exists THEN
    INSERT INTO another_table (col1, col2, col3)
    VALUES(1, 2, 3);
  END IF;
END;
$$ LANGUAGE plpgsql;

但是,您实际上并不需要 IF 语句作为开头。您可以将其简化为单个 INSERT 语句:

INSERT INTO another_table (col1, col2, col3)
SELECT 1,2,3 
WHERE NOT EXISTS (SELECT *
                  FROM some_table 
                  WHERE user_id = new.user_id
                    AND created >= current_date);