- 论坛徽章:
- 3
|
今天看了一个老外的文章,说如何做到让表中只有一条记录: http://www.databasesoup.com/2012 ... xactly-one-row.html
方法比较有趣:
如下所示:
postgres=# CREATE TABLE db_version (
postgres(# version NUMERIC NOT NULL,
postgres(# upgraded_on TIMESTAMPTZ NOT NULL
postgres(# );
CREATE TABLE
postgres=# CREATE UNIQUE INDEX db_version_one_row
postgres-# ON db_version((version IS NOT NULL));
CREATE INDEX
postgres=# INSERT INTO db_version VALUES ( '1.0',now());
INSERT 0 1
postgres=# INSERT INTO db_version VALUES ( '1.1',now());
ERROR: duplicate key value violates unique constraint "db_version_one_row"
关键占在于建了一个函数索引:
CREATE UNIQUE INDEX db_version_one_row ON db_version((version IS NOT NULL));
第一条记录,函数索引计算出的值为true,插第二条记录时,还是算出的为true,这样就违反了唯一性约束。
|
|