无法弄清楚为什么我在case语句中出错

时间:2019-12-05 06:23:50

标签: postgresql plpgsql

BEGIN
IF EXISTS(SELECT * FROM user_likes ul WHERE user_likes.user_id = $2 AND user_likes.comment_id = $1) THEN
    IF(CASE WHEN ul.liked END) THEN
        UPDATE user_likes SET liked = null WHERE user_id = $2 AND comment_id = $1;
        UPDATE event_comments SET num_likes = num_likes - 1 WHERE comment_id = $1;
    ELSE
        UPDATE user_likes SET liked = true WHERE user_id = $2 AND comment_id = $1;
        UPDATE event_comments SET num_likes = num_likes + 1 WHERE comment_id = $1;
    END IF;
ELSE
    INSERT INTO user_likes(comment_id, user_id, liked)
    VALUES($1, $2, true);
    UPDATE event_comments SET num_likes = num_likes + 1 WHERE event_comments.comment_id = 1;

END IF;
END; 

遇到此错误:

ERROR: syntax error at or near "END"
LINE 9: IF(CASE WHEN ul.liked END) THEN

我正在尝试从存在表ul检查ul.liked列是否为真

1 个答案:

答案 0 :(得分:1)

直接的问题是您不需要IF内的CASE表达式:

因此(假设liked确实是boolean列)是这样的:

IF(CASE WHEN ul.liked END) THEN

应为:

IF ul.liked THEN

这假设您有一个名为ul的记录变量,其中包含一个名为liked的字段

但是我认为可以将整个方法简化为单个UPDATE ON CONFLICT语句。并且您不应该将NULL存储为“不喜欢”的标志,我认为在这种情况下最好使用false

类似的东西:

with new_like as (
  INSERT INTO user_likes(comment_id, user_id, liked)
  VALUES($1, $2, true)
  ON CONFLICT (comment_id, user_id) DO UPDATE 
    SET liked = case 
                  when user_likes.liked then null 
                  else excluded.liked
                end
  returning *
) 
UPDATE event_comments 
   SET num_likes = num_likes + case when nl.liked is null then -1 else 1 end
FROM new_like nl
WHERE event_comments.comment_id = nl.comment_id;

或者,或者不使用NULL而是使用false

with new_like as (
  INSERT INTO user_likes(comment_id, user_id, liked)
  VALUES($1, $2, true)
  ON CONFLICT (comment_id, user_id) DO UPDATE 
    SET liked = NOT user_likes.liked --<< simply flips the value 
  returning *
) 
UPDATE event_comments 
   SET num_likes = num_likes + case when nl.liked then -1 else 1 end
FROM new_like nl
WHERE event_comments.comment_id = nl.comment_id;