Write a Postgres Get or Create SQL Query
我想写一个PostgresSQL语句,它说寻找一个颜色为x、亮度为y的用户。如果这个用户存在,返回它的所有行数据。如果没有,则创建一个新行并传递附加信息。这两个独立的语句的作用如下:
1 | SELECT (color, brightness, SIZE, age) FROM mytable WHERE color = 'X' AND brightness= 'Y'; |
如果没有返回任何内容,则执行以下操作:
1 | INSERT INTO mytable (color, brightness, SIZE, age) VALUES (X, Y, big, OLD); |
有没有办法把这些合并成一个查询??
一个SQL数据库的选择试验方法insert是一个错误,没有一prevents过程:从inserting"缺失"的行之间的
1 2 3 4 5 6 7 8 9 10 11 | INSERT INTO mytable (color, brightness, SIZE, age) SELECT color, brightness, SIZE, age FROM mytable WHERE NOT EXISTS ( SELECT 1 FROM FROM mytable WHERE color = 'X' AND brightness = 'Y' ); SELECT (color, brightness, SIZE, age) FROM mytable WHERE color = 'X' AND brightness= 'Y'; |
你应该是能够通,整个文本作为一个单一的"查询"的数据库。你可能想consider制造它,这一stored过程。 </P >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | WITH sel AS ( SELECT color, brightness, SIZE, age FROM mytable WHERE color = 'X' AND brightness = 'Y' ), ins AS ( INSERT INTO mytable (color, brightness, SIZE, age) SELECT 'X', 'Y', 6.2, 40 WHERE NOT EXISTS ( SELECT 1 FROM sel ) returning color, brightness, SIZE, age ) SELECT color, brightness, SIZE, age FROM ins UNION SELECT color, brightness, SIZE, age FROM sel |
如果你participate柱式的独塔,你可以使用一个独特的约束。这是由于现有版本9.5的方法: </P >
1 2 3 | INSERT INTO mytable (color, brightness, SIZE, age) VALUES ('X', 'Y', 'big', 'old') ON CONFLICT (color) DO NOTHING; |
(你认为他有独特的
吉尔:文档是www.postgresql.org https:/ / / / / / sql-insert.html 9.5静电文件 </P >
我在这里adding溶液。这是一个不同的点"和"astef比clodoaldo网的解决方案。 </P >
1 2 3 4 5 6 7 8 9 10 | WITH ins AS ( INSERT INTO mytable (color, brightness, SIZE, age) VALUES ('X', 'Y', 'big', 'old') ON CONFLICT (color) DO NOTHING RETURNING * ) SELECT * FROM ins UNION SELECT * FROM mytable WHERE color = 'X'; |
我发现astef的溶液为我inadequate用途:它不perform"get"portion"或"Create"!如果值已existed,没有什么会happen。 </P >
在尽头的联合声明ensures,如果值是在inserted(因为它已existed)检索值,我们还从黑板。 </P >