回答
這不能單獨使用檢查約束來完成,但有一種使用物化視圖和檢查約束的方法,如我演示here on my blog。爲了您的例子,這會是:
create materialized view emp_dep_mv
build immediate
refresh complete on commit as
select emp_id, count(*) cnt
from relatives
group by emp_id;
alter table emp_dep_mv
add constraint emp_dep_mv_chk
check (cnt <= 3)
deferrable;
然而,這種方法可能不是一個大的,繁忙的生產數據庫高性能,在這種情況下,你可以去使用觸發器和檢查約束的方法,加上一個額外的在員工表列:
alter table employees add num_relatives number(1,0) default 0 not null;
-- Populate for existing data
update employees
set num_relatives = (select count(*) from relatives r
where r.emp_id = e.emp_id)
where exists (select * from relatives r
where r.emp_id = e.emp_id);
alter table employees add constraint emp_relatives_chk
check (num_relatives <= 3);
create trigger relatives_trg
after insert or update or delete on relatives
for each row
begin
if inserting or updating then
update employees
set num_relatives = num_relatives + 1
where emp_id = :new.emp_id;
end if;
if deleting or updating then
update employees
set num_relatives = num_relatives - 1
where emp_id = :old.emp_id;
end if;
end;
我不滿意..我的需求需要一個簡單的約束(在創建表的時候)...一種內外的方法......我認爲在行級別是不可能的,或者是這樣嗎? – 2012-01-09 03:51:54
你是對的:你的要求無法實現。建立一個簡單的約束來執行這個規則是不可能的。 – 2012-01-09 10:53:15
onedaywhen的答案的修訂版本應該能夠解決問題。 – Tripartio 2015-03-24 14:35:39
添加一個新的整數NOT NULL列occurrence
,增加一個檢查約束occurrence BETWEEN 1 AND 3
,對emp_id
和occurrence
複合添加唯一約束,選擇添加輔助特效維持occurrence
值。
- 1. 是否可以約束一個表只有一組列中的一個值
- 2. 我可以有複合約束嗎?
- 3. 我可以在IndexedDb對象庫中指定一個'唯一一起'約束嗎?
- 4. SQL約束在兩列中有一個唯一值
- 5. MySQL:通過數據庫設計,我可以將一個表中的列值約束爲另一個表中的列中的值嗎?
- 6. Oracle sql - 我們可以在同一個表中有2個唯一的列嗎
- 7. 您可以更改列上有外鍵約束的列中的值嗎?
- 8. 我可以在同一個表中有兩個唯一列嗎?
- 9. 我可以在Derby/JavaDB中指定複合唯一約束嗎?
- 10. SQL - 只有UNIQUE或PRIMARY KEY約束可以對計算列創建
- 11. 我可以在SQL Server的添加列語句中創建一個命名的默認約束嗎?
- 12. 具有多個NULL值的SQL中的唯一約束
- 13. 如何約束一個數據庫表,使一列中只有一行可以有特定的值?
- 14. UIStackView可以被約束嗎?
- 15. SQL Server中的可逆唯一約束
- 16. 有沒有辦法可以創建一個約束來檢查SQL Server中兩列的值?
- 17. 我可以有一個可編輯的計算列嗎?
- 18. 具有不可互換值的多列的唯一約束
- 19. 我可以在POSTGRES的視圖中的列中添加默認約束嗎?
- 20. 我可以把多個ListArrays放在同一個h:datatable的不同列中嗎?
- 21. SQL約束:非唯一列中的唯一值
- 22. 在SQL Server中刪除之前可以檢查約束嗎?
- 23. 我們可以在不同表格中的兩個唯一約束之間建立關係嗎?
- 24. 我可以用SQL統計行數並同時獲得列值嗎?
- 25. 我可以忽略「無法同時滿足約束條件」嗎?
- 26. 我可以擁有一個沒有值的JavaScript對象鍵嗎
- 27. 具有日期範圍的不同列中的SQL計數值
- 28. 我可以使用typescript將一個對象鍵約束到一個枚舉值嗎?
- 29. MySQL:約束一組列,所以至少有一個不是NULL
- 30. 以下列表中的至少一個約束可能是您不想要的約束
爲什麼不創建一個觸發器呢? – Nonym 2012-01-07 14:59:26
這可能會有所幫助:http://stackoverflow.com/questions/5522320/what-is-the-best-way-to-enforce-a-subset-relationship-with-integrity-constrain – 2012-01-07 15:02:17