Postgresql upsert在冲突时返回id?

时间:2017-10-15 03:57:42

标签: postgresql

我现在有以下查询,它会在成功插入后返回id

<div class="video_main">
  <video width="100%" height="100%" autoplay="autoplay" loop="loop" muted="muted" preload>
<source src="http://bartonlewisfilm.com/red hook, rush hour (excerpt).mp4" type="video/mp4">
    </video>
    <div class="content">
        <h1>Barton Lewis</h1>
        <h2>films about light and the urban landscape</h2>
        <div class="videolinks">
            <p><a href="index.html" title="home">home</a></p>
            <p><a href="bartons_film_site_works.html" title="works">works</a></p>
            <p><a href="bartons_film_site_bio.html" title="bio">bio</a></p>
            <p><a href="bartons_film_site_cv.html" title="c/v">CV</a></p>        
            <p><a href="bartons_film_site_contact.html" title="contact">contact</a></p>
        </div>
    </div>
    </div>

如何让它返回冲突中已经存在的行的INSERT INTO match (match_id) values(?) ON CONFLICT DO NOTHING RETURNING id

1 个答案:

答案 0 :(得分:1)

使用ON CONFLICT DO UPDATE来确保查询在一行上运行,因此可以返回一些内容:

CREATE TABLE match(id serial PRIMARY KEY);

INSERT INTO match (id) VALUES (1)
ON CONFLICT (id) DO UPDATE
  SET id = excluded.id
RETURNING id;