下面是sql語句:
insert into jd_api_data_20200116 (id,name) select id,city from province_and_city as a where id = 1 on conflict(id) do update set name = EXCLUDED.name;
詳解:
首先呢,基礎語法是這樣的:
insert into xxx on conflict(pkkey) do xxx;
這是一個插入語句觸發器(需要一個主鍵或者唯一索引),當原本數據庫有這條唯一索引的數據時,執行觸發器后語句,否則執行insert語句.
然后呢,上面這句,先執行select 查詢語句,查詢該id對應的記錄的id,city字段值,然后執行insert語句,將查詢的字段值insert到新表中,如果已存在該記錄,那么執行do觸發器后的update語句.
這里update語句中的EXCLUDE.xxx表示前面查詢語句對應的字段值