postgresql 错误:“SELECT”处或附近的语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40824322/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:27:30  来源:igfitidea点击:

ERROR: syntax error at or near "SELECT"

sqldatabasepostgresql

提问by Y_KL

I am really new to postgres. The question looks very simple but I just cant see where I got wrong.

我对 postgres 真的很陌生。这个问题看起来很简单,但我就是看不出哪里错了。

I a table created as follows:

我创建的表如下:

  CREATE TABLE IF NOT EXISTS t(
        tn VARCHAR(30) NOT NULL,
        PRIMARY KEY(tn)
    );

I want to insert an instance if the instance does not exist. Here is my code:

如果实例不存在,我想插入一个实例。这是我的代码:

INSERT INTO t (tn) 
VALUES 
(SELECT 'q' WHERE NOT EXISTS (SELECT * FROM t WHERE tn = 'q')) ;

And the psql console keeps giving me the error

并且 psql 控制台不断给我错误

ERROR:  syntax error at or near "SELECT"

I have checked every piece of code individually, for instance both

我已经单独检查了每一段代码,例如

SELECT 'q' WHERE NOT EXISTS (SELECT * FROM t WHERE tn = 'q');

and

INSERT INTO t (tn) VALUES ('p');

run without error. But error occurs when I put them together.

运行没有错误。但是当我把它们放在一起时会发生错误。

Does anyone know where I got wrong..?

有谁知道我哪里错了..?

采纳答案by Bohemian

Lose VALUESand the brackets...

VALUES和括号...

INSERT INTO t (tn) 
SELECT 'q' WHERE NOT EXISTS (SELECT * FROM t WHERE tn = 'q');