1、数值类型
整数:
mysql中的整数类型和pg相比,两者有以下区别:
mysql:mysql中支持int 1,2,3,4,8 字节,同时支持有符号,无符号。并且mysql中支持在数值列中指定zerofill,用来将存储的数值通过填充0的方式达到指定数据类型的长度(mysql8开始不建议使用ZEROFILL属性,并且在将来的MySQL版本中将不再支持该属性)。
pg:pg支持 int 2,4,8 字节,且数值都是有符号的。
mysql整数类型:
pg整数类型:
那么对于mysql中的1,3字节整型,或者无符号整型以及zerofill特性,在pg中该如何实现呢?
在pg中我们可以使用domain来实现mysql中的1,3字节整数以及无符号整型。
创建uint8,8字节无符号整型
bill=# create domain uint8 as numeric(20,0) check (value <= ((2^64::numeric)::numeric(20,0)-1) and value>=0::numeric(20,0));
CREATE DOMAIN
使用domain,插入整型数据,且大于等于0,小于2^64
bill=# create table t5(c1 uint8);
CREATE TABLE
bill=# insert into t5 values (-1);
ERROR: value for domain uint8 violates check constraint "uint8_check"
bill=# insert into t5 values (0);
INSERT 0 1
bill=# insert into t5 values (18446744073709551615);
INSERT 0 1
bill=# insert into t5 values (18446744073709551616);
ERROR: value for domain uint8 violates check constraint "uint8_check"
bill=# select * from t5;
c1
----------------------
0
18446744073709551615
(2 rows)
同样我们也可以来创建domain实现1,3字节有无符号整型,2,4,8字节无符号等等:
create domain int1 as int2 CHECK (VALUE <= 127 AND VALUE >= (-128));
create domain uint1 as int2 CHECK (VALUE <= 255 AND VALUE >= 0);
create domain uint2 as int4 CHECK (VALUE <= 65535 AND VALUE >= 0);
create domain int3 as int4 CHECK (VALUE <= 8388607 AND VALUE >= (-8388608));
create domain uint3 as int4 CHECK (VALUE <= 16777215 AND VALUE >= 0);
create domain uint4 as int8 CHECK (VALUE <= 4294967295 AND VALUE >= 0);
create domain uint8 as numeric(20,0) check (value <= ((2^64::numeric)::numeric(20,0)-1) and value>=0::numeric(20,0));
而对于mysql中的zerofill,我们可以使用lpad函数来实现,并且这也是mysql官方文档中推荐的一种方式。
mysql中zerofill使用方式:
mysql> create table t1(id int1 zerofill);
Query OK, 0 rows affected (0.0