依赖列约束

时间:2018-05-18 06:07:05

标签: mysql sql

不确定我是否可以使用mysql约束来实现此目的,但是在

这样的表中
CREATE TABLE constraint_table (
    id int PRIMARY KEY AUTOINCREMENT,
    col1 int NOT NULL,
    col2 int NOT NULL
)

是否可以设置mysql约束,以使col2可以为给定的col1

重复
| id | col1 | col2 |
| 1  | 1    | 1    | 
| 2  | 1    | 2    |
| 3  | 1    | 1    |

但特定col2值使用的col1值不能再由另一个col1值使用

| id | col1 | col2 |
| 1  | 1    | 1    | 
| 2  | 1    | 2    |
| 3  | 1    | 1    | 
| 4  | 2    | 1    | invalid - as 1 is included in col2 values where col1 <> 2 (need to restrict this)
| 5  | 2    | 2    | invalid - as 2 is included in col2 values where col1 <> 2 (need to restrict this)
| 6  | 2    | 4    | valid - as 4 is not included in col2 values where col1 <> 2

并且有效表应该是

| id | col1 | col2 |
| 1  | 1    | 1    | 
| 2  | 1    | 2    |
| 3  | 1    | 1    |
| 4  | 2    | 3    |
| 5  | 2    | 4    |
| 6  | 2    | 4    |

抱歉标题不好,我不知道怎么称呼这种情况。

2 个答案:

答案 0 :(得分:0)

玩得开心!

pthread_attr_setdetachstate()

答案 1 :(得分:0)

我认为您的数据格式错误。您似乎希望每个QSub any = exp.sub.any(); builder.and( any.selected.isTrue().and(any.sub.person.id.eq(user.getId())))); 都有col1个值。这表明了一个用于此目的的表:

col2

然后你的表可以是:

create table2 (
    col2 int primary key,
    col1 int not null,
);

CREATE TABLE constraint_table ( id int PRIMARY KEY AUTOINCREMENT, col2 int NOT NULL, . . . -- I assume there are other tables here foreign key (col2) references table2(col2) ); 不属于此表,因为它严格依赖于col1。所以,这一对进入第一个表 - 一行。

相关问题