我有屬性類型和值字段的屬性表。如何維護數據庫中的唯一值?
AttrType -- AttrValue
----------------------------------
attr1 -- value1
attr2 -- value2
attr3 -- value3
attr1 -- value1
我需要確保屬性類型'attr1'必須具有唯一值。 像上面一樣,我需要避免的attr1重複了value1。
是否有任何數據庫級別檢查可以添加到表上?
我有屬性類型和值字段的屬性表。如何維護數據庫中的唯一值?
AttrType -- AttrValue
----------------------------------
attr1 -- value1
attr2 -- value2
attr3 -- value3
attr1 -- value1
我需要確保屬性類型'attr1'必須具有唯一值。 像上面一樣,我需要避免的attr1重複了value1。
是否有任何數據庫級別檢查可以添加到表上?
添加唯一約束到表:
alter table tablename add constraint constraintname unique(AttrType, AttrValue)
(也可以做到,當create table
。)
嗨jarlh,但有了這個,我們對attr2和attr3也會有一些限制。我只想要attr2值的唯一約束。 – user1298426
這很麻煩。我不認爲Postgresql有任何內置的功能來做到這一點。我會考慮基於觸發的解決方案。 – jarlh
@ user1298426類似於在表名(AttrValue)上創建唯一索引idx_tablename_attr1,其中AttrType ='attr1';'查找[部分索引](https://www.postgresql.org/docs/9.5/static/sql-createindex。 HTML) – Abelisto
添加約束'獨特(AttrType,AttrValue)'。 – jarlh