Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于共享的SQL规则/约束_Sql_Postgresql - Fatal编程技术网

用于共享的SQL规则/约束

用于共享的SQL规则/约束,sql,postgresql,Sql,Postgresql,我有一个由列组成的表: device_id account_id is_owner 将设备id和帐户id作为聚合主键 我如何创建一个SQL规则/约束,以便当“is_owner”与“congregate primary key”的值为true时,它将不允许另一个SQL规则/约束的组合 device_id = (specific device id) account_id = (any account id) is_owner = true 因为设备的所有者应该只有一个 而且: device_

我有一个由列组成的表:

device_id
account_id
is_owner
将设备id和帐户id作为聚合主键

我如何创建一个SQL规则/约束,以便当“is_owner”与“congregate primary key”的值为true时,它将不允许另一个SQL规则/约束的组合

device_id = (specific device id)
account_id = (any account id) 
is_owner = true
因为设备的所有者应该只有一个

而且:

device_id  = (specific device id)
account_id = (any account id)   
is_owner = false

可以是“多个”,因为所有者帐户可以将设备共享给另一个帐户?

您可以使用部分索引:

CREATE UNIQUE INDEX idx_name 
   ON table_name(device_id, account_id)       --or only (device_id) if needed
WHERE is_owner = true;

例如:

CREATE TABLE t(device_id INT NOT NULL, account_id INT NOT NULL, is_owner BOOL);
CREATE UNIQUE INDEX idx_name ON t(device_id, account_id)
WHERE is_owner = true;
INSERT INTO t(device_id, account_id, is_owner)
VALUES( 1,1, false),(1,1,false);

SELECT * FROM t;

INSERT INTO t(device_id, account_id, is_owner)
VALUES( 1,2, true),(1,2,true);
--ERROR:  duplicate key value violates unique constraint "idx_name"
--DETAIL:  Key (device_id, account_id)=(1, 2) already exists.