postgresql替换mysql相关

postgresql替换mysql相关

最近需要将数据库从mysql切换到postgresql,顺便记录一下相关信息;

文章目录

    • postgresql替换mysql相关
      • 函数替换
        • timestampdiff 函数
        • date_format 函数
        • if 函数
        • ifnull
      • 表中字段类型不相同不能比较
      • 多个数据拼接
      • 序列

函数替换

mysql中一些函数在postgresql是没有定义的,需要自行创建

timestampdiff 函数
create or REPLACE FUNCTION timestampdiff(HOUR text,create_time TIMESTAMP,end_time TIMESTAMP)
    RETURNS BIGINT
as
$$
BEGIN
    if upper($1)='SECOND' then
        return  trunc(extract(EPOCH FROM ($3 - $2::TIMESTAMP)) )::bigint;
    end if;
    if UPPER($1)='HOUR' then
        return  trunc(extract(EPOCH FROM ($3 - $2::TIMESTAMP)/3600) )::bigint;
    end if;
    if upper($1)='DAY' then
        return  trunc(extract(EPOCH FROM ($3 - $2::TIMESTAMP)/3600/24) )::bigint;
    end if;
    if upper($1)='MONTH' then
        return  trunc(extract(EPOCH FROM ($3 - $2::TIMESTAMP)/3600/24/30) )::bigint;
    end if;
    if upper($1)='YEAR' then
        return  trunc(extract(EPOCH FROM ($3 - $2::TIMESTAMP)/3600/24/365) )::bigint;
    end if;
end;
$$
    LANGUAGE plpgsql

date_format 函数
CREATE OR REPLACE FUNCTION date_format(indate anyelement, intext text)
 RETURNS text
 LANGUAGE plpgsql
AS $function$
BEGIN
IF upper(inText) = upper('%Y%m%d_%H%i') THEN
return to_char(inDate,'YYYYMMDD_HH24MI');
END IF;
IF upper(inText) = upper('%Y%m%d%H%i%s') THEN
return to_char(inDate,'YYYYMMDDHH24MISS');
END IF;
IF upper(inText) = upper('%Y-%m-%d %H') THEN
return to_char(inDate,'YYYY-MM-DD HH24');
END IF;
IF upper(inText) = upper('%Y-%m-%d') THEN
return to_char(inDate,'YYYY-MM-DD');
END IF;
IF upper(inText) = upper('%Y-%m') THEN
return to_char(inDate,'YYYY-MM');
end if;
IF upper(inText) = upper('%m%d') THEN
return to_char(inDate,'MMDD');
END IF;
return '';
END;
$function$
if 函数
create or replace function if(bln boolean,inValue1 anyelement,inValue2 anyelement)
returns anyelement as
$$
begin
if bln=true then
   return inValue1;
else
   return inValue2;
end if;
end;    
$$
language plpgsql;

也可使用 case when代替

SELECT CASE WHEN 1 > 2 then 1 else 4 end;
ifnull

mysql中的ifnull()函数对应postgresql的COALESCE

COALESCE('字段名称','期望值')

表中字段类型不相同不能比较

  • 数字转字符串
  to_char(12345, '9999999999999999999')
  • 字符串转数字
  to_number(tt.create_by, '9999999999999999999')

多个数据拼接

分隔符separator可以自己选

select address, array_to_string(array_agg(name order by name), '%') from group_concat group by address;
select address, array_to_string(array_agg(name order by name), ',') from group_concat group by address;
select address, array_to_string(array_agg(distinct name order by name), ',') from group_concat group by address;

序列

-- 设置序列值从0开始
SELECT setval('"test_c_id_seq"', 0, true);
-- 设置自增长字段从当前数据库自增长字段中最大的开始
select setval('要修改的序列名称', (select max(id)  from your_table));
select setval('test_c_id_seq', (select max(id)  from test_table));
-- 返回下一个序列号
select nextval(seq_ commodity);
-- 返回当前的序列号
select currval(seq_ commodity);

你可能感兴趣的:(postgresql,mysql)