我可以在postgres 9.4中写这样的东西吗?
SELECT id FROM image_instance WHERE name = 'bioboxes/velvet-then-quast'
UNION ALL
INSERT INTO image_instance (name, sha256, image_type_id)
SELECT
'bioboxes/velvet-then-quast',
'digest_4',
(SELECT id FROM image_type WHERE name = 'short_read_preprocessing_reference_evaluation')
WHERE NOT EXISTS (SELECT id FROM image_instance WHERE name = 'bioboxes/velvet-then-quast')
RETURNING id
我在INSERT
上遇到语法错误,所以我认为这是不可能的?我认为值得一提,以防我写错了。
我知道这不是线程安全的,但这适用于单线程应用程序。
答案 0 :(得分:2)
看来你是在这之后。只需将INSERT
包裹到CTE中(使用WITH):
WITH
CTE
AS
(
INSERT INTO image_instance (name, sha256, image_type_id)
SELECT
'bioboxes/velvet-then-quast',
'digest_4',
(SELECT id FROM image_type WHERE name = 'short_read_preprocessing_reference_evaluation')
WHERE NOT EXISTS (SELECT id FROM image_instance WHERE name = 'bioboxes/velvet-then-quast')
RETURNING id
)
SELECT id FROM image_instance WHERE name = 'bioboxes/velvet-then-quast'
UNION ALL
SELECT id FROM CTE
;
此查询会在image_instance
中插入一些行;生成的id
列值将由RETURNING
子句返回;反过来来自UNIONed ALL
的{{1}}的{{1}}值为id
。
我不确定结果是什么,你应该检查,但语法应该是正确的。