一個表有a,b兩個欄位,b有生效和失效兩個狀態,要保證b為生效狀態時,a欄位唯一,有沒有資料庫解決方案,失效狀態可能是多個,所以ab聯合不是唯一的
uj5u.com熱心網友回復:
SQL> create table t(a int, b int);
Table created
SQL> create unique index iux_t_ab on t(decode(b, 0, null,a));
Index created
SQL> -- b = 0 時,a可以有重復值
SQL> insert into t values(100, 1);
1 row inserted
SQL> insert into t values(100, 0);
1 row inserted
SQL> insert into t values(100, 0);
1 row inserted
SQL> insert into t values(200, 1);
1 row inserted
SQL> insert into t values(200, 1); -- 這行失敗
insert into t values(200, 1)
ORA-00001: 違反唯一約束條件 (ORACLE.IUX_T_AB)
SQL> insert into t values(200, 0);
1 row inserted
SQL> select * from t;
A B
---- ----
100 1
100 0
100 0
200 1
200 0
SQL> drop table t purge;
Table dropped
SQL>
uj5u.com熱心網友回復:
資料量少select * from table where a in (
select a from table where b='有效' group by a having count(*)=1);
資料量多,子查詢建臨時表
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/57041.html
標籤:開發
