Postgres:执行具有条件的函数:CASE WHEN EXISTS

时间:2016-08-09 05:21:25

标签: sql postgresql

我正在尝试执行此功能:

SELECT CASE WHEN EXISTS (
  SELECT id
  FROM public.contributor
  WHERE owner = '7d132812-4828-4a48-807c-5f5d7a459447' AND library = '45781650-11d1-4f66-b11b-23a7e761f224'
)
THEN
    UPDATE public.contributor SET commits = contributor.commits + 1 WHERE owner = '7d132812-4828-4a48-807c-5f5d7a459447' AND library = '45781650-11d1-4f66-b11b-23a7e761f224'
ELSE
    INSERT INTO public.contributor (name, commits, image, library, owner)
    SELECT owner_name, 1, owner_image, library, owner FROM public.commit WHERE id = 'e3c8a92a-64c7-408a-baa4-d80f47c3d3c3'
END

但它不断返回语法错误:

ERROR:  syntax error at or near "public"
LINE 7:  UPDATE public.contributor SET commits = contributor.commits...

此功能的每一部分彼此分开工作:
1

SELECT CASE WHEN EXISTS (
  SELECT id
  FROM public.contributor
  WHERE owner = '7d132812-4828-4a48-807c-5f5d7a459447' AND library = '45781650-11d1-4f66-b11b-23a7e761f224'
)
THEN
    true
ELSE
    false
END

2

UPDATE public.contributor SET commits = contributor.commits + 1 WHERE owner = '7d132812-4828-4a48-807c-5f5d7a459447' AND library = '45781650-11d1-4f66-b11b-23a7e761f224'

3

INSERT INTO public.contributor (name, commits, image, library, owner)
    SELECT owner_name, 1, owner_image, library, owner FROM public.commit WHERE id = 'e3c8a92a-64c7-408a-baa4-d80f47c3d3c3'

这3个功能中的每一个都可以正常工作,但它们一起工作不起作用。我的错误在哪里?

我可以使用ON CONFLICT运算符代替这种结构吗?

1 个答案:

答案 0 :(得分:1)

select *
from products
order by field(statusid, 3, 1, 2)