测试没有意义,只需在 where 子句中包含“测试”即可:
INSERT INTO silly_table(the_text)
'literal_text'
WHERE NOT EXISTS (
SELECT *
FROM silly_table
WHERE the_text = 'literal_text'
);
现在,您将仅在需要时进行测试:在语句的末尾,该行将存在。没有尝试这样的东西。
对于那些不了解测试没有意义的人:如果测试后的情况不允许在测试后改变,那么测试是有意义的。那将需要一个测试和锁定方案。或者,更糟糕的是:交易中的测试。
更新:有效的版本(基本相同):
DROP TABLE exitsnot CASCADE;
CREATE TABLE exitsnot
( id SERIAL NOT NULL PRIMARY KEY
, val INTEGER -- REFERENCES something
, str varchar -- REFERENCES something
);
INSERT INTO exitsnot (val)
SELECT 42
WHERE NOT EXISTS (
SELECT * FROM exitsnot
WHERE val = 42
);
INSERT INTO exitsnot (str)
SELECT 'silly text'
WHERE NOT EXISTS (
SELECT * FROM exitsnot
WHERE str = 'silly text'
);
SELECT version();
输出:
DROP TABLE
NOTICE: CREATE TABLE will create implicit sequence "exitsnot_id_seq" for serial column "exitsnot.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "exitsnot_pkey" for table "exitsnot"
CREATE TABLE
INSERT 0 1
INSERT 0 1
version
----------------------------------------------------------------------------------------------
PostgreSQL 9.1.2 on i686-pc-linux-gnu, compiled by gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3, 32-bit
(1 row)