PGSQL避坑
1.无论使用insert into students (id,name)values(default,'张三')还是insert into students values(default,'张三')或者insert into students (name) values('张三'),如果有人用显示的主键1写入,那么当default=1时都会报主键1已存在的错。
解决办法是每次手动写入后用select setval(sequenceName, n, true)重置下,详见http://blog.chinaunix.net/uid-26969873-id-4914237.html
2.允许其他电脑访问:数据目录-> pg_hba.conf 添加 host all all 0.0.0.0/0 trust
3.将字符串字段转时间格式:to_char(to_timestamp(starttime,'yyyy-MM-dd HH24:mi:ss.ms'),'yyyy-MM-dd HH24:mi:ss.ms')
4.默认不锁定任何表,不需要 (no lock)
5.行列转换https://blog.csdn.net/weixin_34388207/article/details/91424011
行转列用case when 或者filter (where ),字符串可以用max代替sum
select student,sum(case course when '语文' then score else 0 end) as 语文, sum(case course when '数学' then score else 0 end) as 数学, sum(case course when '英语' then score else 0 end) as 英语 from score group by student
列转行
select empid,key as k,value::text as cardid from ( select empid,row_to_json(row(cardid,cardid2,cardid3,cardid4)) as n from employee t )as r join lateral json_each_text(r.n) on (value is not null and value!='')
6.不支持+=,不支持++
7.列不存在则添加 ALTER TABLE table1 ADD if not exists name text;
8.用as后跟中文列名时,不用单引号
9.创建存储过程或函数成功,但是用Npgsql调用时报错:plpgsql query has no destination for result data
遇见这种情况最好用工具执行下,看看具体报错的行号,将变量(p_开头)赋值语句改成以下形式
1> p_index = 1;
2>p_count =(select count(1) from table1);
3>select id,name into p_id,p_name from table1 where ...;
10.非过程非函数的语句使用if需要do $$ begin ... end $$; 但是不能像简单的语句那样,将类似@id的参数可以用NpgsqlCommand添加@id的参数,只能把参数值拼到sql中,否则报错,就很迷。