在外键字段中插入空字符串值

whhtz7ly  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(249)

我在尝试用 '' 在外键字段中。
我使用postgresqlv10。
我的sql代码:

CREATE TABLE meas_name (
    nopol varchar(2) NOT NULL,
    cchim varchar(10) NOT NULL,
    ncon varchar(30) NOT NULL,
    PRIMARY KEY (nopol)
);

CREATE TABLE main_device (
    ntypapp smallint NOT NULL,
    no_main smallint NOT NULL,
    lib_main varchar(25),
    nopol varchar(2),
    no_chrono smallint,
    PRIMARY KEY (no_main,ntypapp)
);

ALTER TABLE main_device ADD CONSTRAINT fk_maindevice_measname FOREIGN KEY (nopol) REFERENCES meas_name(nopol) ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;

当我用一个已知的设备插入某个度量值时,我有一个错误:

insert into main_device values 
(1, 1, 'TST LASER','',1578)

ERROR: insert or update on table « main_device » violates foreign key constraint « fk_maindevice_measname »
DETAIL: Key (nopol) = () is not present in table « meas_name ».

我已经测试过了:https://www.db-fiddle.com/f/fbnnsywu8qzwfbmeou5dce/1
oracle数据库没有问题,但我对postgres了解不多,有什么限制吗?我该怎么办?

k5ifujac

k5ifujac1#

不支持空字符串 NULL . 使用 NULL :

insert into main_device (ntypapp, no_main, lib_main, nopol, no_chrono)
    values (1, 1, 'TST LASER', NULL, 1578);

NULL 值不需要与外键约束匹配(在此上下文中, NULL 指“无价值”)。但是,空字符串是一个有效值,数据库希望引用的表中有一个匹配的行。
我还添加了显式列名,因为这是最佳实践。

相关问题