1. 程式人生 > >一些幾個經典的postgresql的sql語句

一些幾個經典的postgresql的sql語句

1.強制型別轉換:
1.1. select created_at::date from user
1.2. select created_at::varchar from user
1.3 select cast(created_at as date) from user

2.伴隨語句查詢
2.1. with tmp as (select name,age from user),
tmp2 as (select sal,join_at from company)
select * from user_detail,tmp,tmp2 where user_age = tmp.age [

3.批量插入
3.1 insert into user(name,age) select name,age from account

4.內嵌條件語句
4.1 select case when t.result=‘success’ then 0 else 1 end from table_result as t

5.無返回值且可以重複執行的函式

--將account中在t這一天時間裡新增的使用者同步到user表裡
create function synchronize_user(t date) returns void as 
$$
begin
delete from user
where created=t; insert into user(name,age) select name,age from account where created=t; end; $$ LANGUAGE 'plpgsql' VOLATILE;

呼叫方式:

select synchronize_user('2018-08-17')

6.函式名過載

--將account中所有的使用者同步到user表裡,可以與5並存
create function synchronize_user() returns void as 
$$
begin
delete from
user; insert into user(name,age) select name,age from account; end; $$ LANGUAGE 'plpgsql' VOLATILE;

呼叫方法:

select synchronize_user()

7.建立檢視

create view tmp as 
  (
	select user_id,created,sum(total_money) 
	from orders 
	group by user_id,created 
  )

使用時:

select * from tmp where created='2018-09-02'

8.自定義遞增序列及使

CREATE SEQUENCE 
index_sequence 
START WITH 13 --自定義自增長開始的值 
INCREMENT BY 1 --每次遞增多少 
NO MINVALUE 
NO MAXVALUE 
CACHE 1
create table t(
id integer default nextval('index_sequence')
)

9.伴隨語句與批量插入同時進行

with tmp as (
select user_id,sum(money) as money from users group by user_id
)
insert into money_analysis(user_id,money) select * from tmp

10.左右全連接出現的null處理補0或者補’’

--student的id比class_student的student的id多,造成了一些補充資料null
--對fee補0,對introduction補''
select student.id,
       case when fee is null then 0 else fee end ,
       case when introduction is null then '' else introduction
from student left join class_student on student.id = class_student.student_id
  1. 返回table的函式
/*注意點
12. table宣告的引數數量和型別要和內部的select一致,但取名不能一致,不然會衝突。
13. 呼叫時,對於插入修改刪除型別的可以使用select fun(),但是對於select最好使用select * from fun(),因為select fun()對select查詢會返回出raw message,比如(1,'fw',9)而不是 user_id|name|age \n 1|'fw'|9
*/
create function find_master() returns table(nm varchar,uid integer,ag integer) as
$$
begin
return query
(
 select name,user_id,age from tuser
);
end;
$$
language 'plpgsql' volatile;

使用時:

select * from find_master()
-- 千萬不要使用,這是資料流
select find_master()
  1. 邏輯取反
    並沒有查到官方的取反操作,只有自己寫了

create or replace function getnot(arg boolean) returns boolean as
$BODY$
begin
	if arg=true then
		return false;
	else 
		return true;
	end if;
end;
$BODY$
language 'plpgsql' volatile;

使用時:

-- 選出使用者表裡,排除掉 id >5 且age < 3 的使用者
select * from tuser where getnot(id>5 and age<3)