如果不存在,则 Postgresql 插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27083330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Postgresql insert if not exists
提问by daryl
I'm very new to SQL, and all I get is error after error, so any help would be appreciated.
我对 SQL 很陌生,我得到的只是一个又一个错误,所以任何帮助都将不胜感激。
I have a tags table: id, name, slug
我有一个标签表:id、name、slug
I've Google'd, searched on Stackoverflow, but nothing works for me. I'm trying to create a tag if it doesn't exist, but always return the ID whether it's created or exists.
我已经谷歌搜索过,在 Stackoverflow 上搜索过,但对我来说没有任何效果。如果标签不存在,我正在尝试创建它,但无论它是创建还是存在,总是返回 ID。
INSERT INTO tags (name, slug)
SELECT ('Wow', 'wow')
WHERE NOT EXISTS (SELECT id FROM tags WHERE slug = 'wow')
RETURNING id;
Here's what I have: http://sqlfiddle.com/#!15/4050a/18
这是我所拥有的:http: //sqlfiddle.com/#!15/4050a/18
回答by a_horse_with_no_name
Don't put the columns in parentheses.
不要将列放在括号中。
If you look at the full error message you get, then Postgres actually tells you what was wrong.
如果您查看获得的完整错误消息,那么 Postgres 实际上会告诉您出了什么问题。
ERROR: INSERT has more target columns than expressions
Hint: The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?
错误:INSERT 的目标列比表达式多
提示:插入源是一个行表达式,其中包含与 INSERT 期望的列数相同的列数。您是否不小心使用了额外的括号?
The expression ('Wow', 'wow')
is just a singlecolumn, an anonymous "record" with two variables (See the manualfor details)
表达式('Wow', 'wow')
仅仅是一个单一的柱,一个匿名的“记录”与两个变量(见手册的详细信息)
INSERT INTO tags (name, slug)
SELECT 'Wow', 'wow'
WHERE NOT EXISTS (SELECT id FROM tags WHERE slug = 'wow')
RETURNING id;
In general it's a good idea to add parentheses only if they are really required
一般来说,只有在真正需要时才添加括号是个好主意
回答by peter.petrov
(1) Just remove the brackets. That should solve your problem.
(1) 只需删除括号。那应该可以解决您的问题。
INSERT INTO tags (name, slug)
SELECT 'Wow', 'wow'
WHERE NOT EXISTS (SELECT id FROM tags WHERE slug = 'wow')
RETURNING id;
(2) Try this. That should also do it (even though a FROM
clause is not actually needed as others pointed out).
(2) 试试这个。这也应该这样做(即使
其他人指出的实际上并不需要FROM子句)。
INSERT INTO tags (name, slug)
SELECT 'Wow', 'wow' FROM tags
WHERE NOT EXISTS (SELECT id FROM tags WHERE slug = 'wow')
LIMIT 1
RETURNING id;