postgresql插入null转换为默认值?

时间:2018-04-24 02:25:04

标签: mysql postgresql hibernate

MySQL中有一些功能但postgresql中没有。 1.创建一个表并给出一个列默认值 2.将空值插入表中。 在MySQL中,它将插入默认值; 在postgresql中它将插入null值; 如何使postgresql像MySQL一样。 我在更改DBMS期间发现了这个问题。我的应用程序是java中的代码。 ORM是Hibernate 5.1.0。 我更改DBMS然后很多默认列不起作用。

MySQL sql

drop table table1;
CREATE TABLE table1
(
  column_1 int PRIMARY KEY AUTO_INCREMENT,
  column_2 timestamp DEFAULT current_timestamp
);
insert into table1(column_2) values(null);
select * from table1;

结果

| column_1 | column_2            |
+----------+---------------------+
|        1 | 2018-04-24 10:00:18 |

的pgsql

drop table table2;
CREATE TABLE table2
(
column_1 serial PRIMARY KEY,
column_2 timestamp DEFAULT current_timestamp
);
insert into table2(column_2) values (null);
select * from table2;

结果

 column_1 | column_2 
----------+----------
        1 | 

2 个答案:

答案 0 :(得分:1)

我认为如果你想在插入时获得默认值,我建议你使用3种方法:

  1. 不要把它放在你的查询中。
  2. 使用关键字DEFAULT AS insert into table2(column_2) values (DEFAULT);
  3. 在插入时编写触发器并处理数据。
  4. 希望我的回答能帮到你。

答案 1 :(得分:0)

这将插入null。

test=# insert into table2(column_2) values (null);
INSERT 0 1
test=# select * from table2;
 column_1 | column_2 
----------+----------
        1 | [null]
(1 row)

插入并且不包含具有默认值的列时,将插入其默认值。我猜你有一个可用于此的序列。

test=# insert into table2(column_1) select max(column_1)+1 from table2;
INSERT 0 1
test=# select * from table2;
 column_1 |          column_2          
----------+----------------------------
        1 | [null]
        2 | 2018-04-24 03:44:10.669642
(2 rows)
相关问题