版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fwhezfwhez/article/details/81738781
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
- 返回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()
- 逻辑取反
并没有查到官方的取反操作,只有自己写了
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)