postgres sql語句總結

2021-10-13 12:58:44 字數 2721 閱讀 6749

建立表:

create table tablename 

(field1 integer not null peimary key, //int,不為空,主鍵

field2 character varying(10) not null, //char,10個位元組,不為空

field3 serial not null, //int,自增,不為空

field4 text, //char,文字

field5 numeric, //int,數字

field6 timestamp without time zone, //不帶時區的時間

field7 numeric default 0) //int,數字,預設0

插入資料:

insert into tablename(field1,field2,field3) values(1,'%2',3,'%4',5,'2060-06-06','7')
查詢某字段不為空(為空):

//不為空

select * from "tablename" where "fieldname" is not null

//為空

select * from "tablename" where "fieldname" is null

計算某長度字段長度:

select sum("field") from "tablename"
統計某欄位個數:

select count("field") from "tablename"
查詢某欄位範圍內資料:

select "filed" from "tablename" where "field" between '' and ''
查詢某欄位符合條件:

select "fieldname" from "tablename" where "field" ~* '^%1$'//全匹配%1

select "fieldname" from "tablename" where "field" ~* '%1'//不匹配%1

select "fieldname" from "tablename" where "field" ~* '%1$'//後匹配%1

select "fieldname" from "tablename" where "field" ~* '^%1'//前匹配%1

//多條件查詢

select "fieldname" from "tablename" where "field1" ~* '%1' and "field2" ~* '%2'

select "fieldname" from "tablename" where "field" ~* '%1' or "field" ~* '%2'

//跨表查詢

select "fieldname1" from "tablename1" where "field1" in (select "fieldname2" from "tablename2" where "field2" ~* '%1')

//通過多條件查詢跨表統計某欄位個數

select count(*) from "tablename1" where "fieldname1" in (select "fieldname2" from "tablename2" where ("field1" ~* '%1' or "field1" ~* '%2') and ("filed2" between '%3' and '%4') ) or "fieldname3" in (select "fieldname4" from "tablename3" where ("filed3" ~* '%5'))

查詢某字段中的資料存在且不重複

select distinct "field" from "tablename" where "field" is not null
同表拼接多字段去重查詢

最終查詢的字段必須在group by裡出現

select concat("fieldname1","fieldname2"),"fieldname1" from "tablename" group by concat("fieldname1","fieldname2")//查詢拼接fieldname1,filedname2欄位不重複資料

select "fieldname1" from (select concat("fieldname2","fieldname3"),"fieldname1" from "tablename" group by concat("fieldname2","fieldname3"),"fieldname1") name

//查詢欄位fieldname1,條件是滿足拼接fieldname2,fieldname3後不重複的資料

//name是from需求的別名

例項:查詢圓柱體表的直徑與高資料,每個圓柱體的唯一識別符號是頭尾結點,條件是圓柱體不重複

select "d_s","length" from (select concat("s_point","e_point"),"d_s","length" from table

group by concat("s_point","e_point"),"d_s","length") sum

postgres sql 備份還原

postgresql自帶乙個客戶端pgadmin,裡面有個備份,恢復選項,也能對資料庫進行備份 恢復 還原 但最近發現資料庫慢慢龐大的時候,經常出錯,備份的檔案過程中出錯的機率那是相當大,手動調節灰常有限。所以一直尋找完美的備份恢復方案。用法 備份資料庫 指令如下 pg dump h 164.82....

Postgres SQL儲存函式引數使用說明

在使用postgres資料庫的過程中,遇到了表分割槽的問題。為了建立表分割槽,首先得建立分割槽表。首先想到的是寫個儲存函式,然後定時的建立分割槽表,然後再建立觸發器去操作分割槽表。但是在建立儲存函式時,怎麼把分割槽表的表名當作引數傳進儲存函式,然後在函式內部動態建立表。可是直接使用字串的表名不起作用...

PostgresSQL常用客戶端命令

連線資料庫,預設的使用者和資料庫是postgres psql u user d dbname 切換資料庫,相當於mysql的use dbname c dbname 列舉資料庫,相當於mysql的show databases l 列舉表,相當於mysql的show tables dt 檢視表結構,相當...