Postgresql

postgresql relation “xxx” already exists

  1. DROP TALBE XXX

类型转换

  1. cast(character varying as numeric)
  2. double precision

修改列类型

  1. ALTER TABLE the_table ALTER COLUMN col_name TYPE integer USING (col_name::integer)

去重

  1. -- 去重多个列
  2. SELECT DISTINCT code,name from test_dist
  3. -- 查询重复数据
  4. select distinct id, count(*) from emp group by id having count(*) > 1
  5. -- 查询要保留的数据
  6. select ctid, * from emp where ctid in (select min(ctid) from emp group by id)
  7. -- 删除重复数据
  8. delete from emp where ctid not in (select min(ctid) from emp group by id);
  9. -- 删除重复数据
  10. delete from ship_mmsi where id in (select min(id) from ship_mmsi group by name_en having count(*) > 1)

链接其他数据库

  1. create extension dblink;
  2. select * from
  3. dblink('dbname=aaa host=localhost port=5432 user=postgres password=953598751'::text,'select * from pier_point'::text) t
  4. (gid integer,name character varying,geom geometry)

重置 id

  1. alter sequence 表名_序列字段_seq restart with 1;
  2. eg: alter sequence test_gid_seq restart with 70

GeoJson

  1. SELECT row_to_json(fc) geojson
  2. FROM ( SELECT 'FeatureCollection' AS type , array_to_json(array_agg(f)) AS features
  3. FROM (SELECT 'Feature' AS type ,ST_AsGeoJSON(geom)::json as geometry
  4. ,(SELECT row_to_json(t) FROM (SELECT name,gid) AS t) AS properties
  5. FROM fence_anchor
  6. where geom is not null
  7. ) AS f
  8. ) AS fc

主键存在在忽略

  1. insert into ship_ais (mmsi,imo) values ('1','4124') ON conflict(mmsi) DO NOTHING;

主键存在则更新

  1. insert into ship_ais (mmsi,imo) values ('1','1111') ON conflict(mmsi) DO UPDATE SET imo = '1111'