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

Thé*_*lia -1 sql postgresql foreign-keys

\'\'尝试在外键字段中插入带有 a 的值时出现错误。

\n

我使用 PostgreSQL v10。

\n

我的sql代码:

\n
CREATE TABLE meas_name (\n    nopol varchar(2) NOT NULL,\n    cchim varchar(10) NOT NULL,\n    ncon varchar(30) NOT NULL,\n    PRIMARY KEY (nopol)\n);\n\nCREATE TABLE main_device (\n    ntypapp smallint NOT NULL,\n    no_main smallint NOT NULL,\n    lib_main varchar(25),\n    nopol varchar(2),\n    no_chrono smallint,\n    PRIMARY KEY (no_main,ntypapp)\n);\n\nALTER TABLE main_device ADD CONSTRAINT fk_maindevice_measname FOREIGN KEY (nopol) REFERENCES meas_name(nopol) ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE;\n \n
Run Code Online (Sandbox Code Playgroud)\n

当我用已知的设备插入测量的东西时,出现此错误:

\n
insert into main_device values \n(1, 1, \'TST LASER\',\'\',1578)\n\nERROR: insert or update on table \xc2\xab main_device \xc2\xbb violates foreign key constraint \xc2\xab fk_maindevice_measname \xc2\xbb\nDETAIL: Key (nopol) = () is not present in table \xc2\xab meas_name \xc2\xbb.\n
Run Code Online (Sandbox Code Playgroud)\n

我已经对其进行了测试: https: //www.db-fiddle.com/f/fBnNSYWU8qZwFbmEoU5dce/1

\n

Oracle数据库没有问题,但是我对Postgres不太了解,有什么限制吗?我该如何处理这个问题?

\n

Gor*_*off 5

空字符串不是NULL。使用NULL

insert into main_device (ntypapp, no_main, lib_main, nopol, no_chrono)
    values (1, 1, 'TST LASER', NULL, 1578);
Run Code Online (Sandbox Code Playgroud)

NULL不需要与外键约束匹配(在此上下文中,NULL意味着“无值”)。但是,空字符串是有效值,并且数据库期望引用的表中存在匹配的行。

我还添加了显式列名称,因为这是最佳实践。