2017-04-18 44 views
0

我有一个包含ID,Col1和Col2,Col3的表“Table”。 Col2可以是0或1. 我希望Col2在Col1具有相同值的行中相同。 防爆基于另一列的列上的约束

我想是这样的

+----+-------+------+-----------+ 
| ID | Col1 | Col2 | Col3 | 
+----+-------+------+-----------+ 
| 1 | "One" | 0 | "Yeah" | 
| 2 | "One" | 0 | "Meh"  | 
| 3 | "One" | 0 | "Why Not" | 
| 4 | "Two" | 1 | "Huh"! | 
+----+-------+------+-----------+ 

而且不

+----+-------+------+-----------+ 
| ID | Col1 | Col2 | Col3 | 
+----+-------+------+-----------+ 
| 1 | "One" | 0 | "Yeah" | 
| 2 | "One" | 0 | "Meh"  | 
| 3 | "One" | 1 | "Why Not" | (Normally it must be 0 or line 1 and 2 
| 4 | "Two" | 1 | "Huh"! | Must be "1") 
+----+-------+------+-----------+ 
+1

即使在查看您的预期输出之后,仍不清楚您想要什么。但有一件事,如果你想拥有基于其他列值的'col2',那么它就是计算列,并且最好不要存储计算值,而是在提取数据时进行计算。 –

+1

何况你的输入表中的数据,你在输出 –

+0

想要什么,也许与此有关:http://stackoverflow.com/questions/7522026/how-do-i-add-a-check-constratint-to-a-table? - 您的条件应该检查​​的时间不确定:输入时,还是您想要创建更新脚本? – cypherabe

回答

0

即使在MySQL支持的检查约束,你不会有check约束做到这一点。我认为最好的方法是使用外键约束。

你需要第二个表与有效col1/col2值:

create table Col1Col2 as (
    col1 varchar(255) not null primary key, 
    col2 int not null, 
    unique (col1, col2) -- this is not strictly necessary see below 
); 

那么你的表是:

create table t as (
    id int auto_increment primary key, 
    col1 varchar(255) not null, 
    col2 int not null 
    col3 int, 
    constraint fk_t_col1_col2 foreign key (col1, col2) references col1col2(col1, col2) 
); 

不过,我甚至不会存储在col2t。请将其从t中删除,只需查看col1col2中的值即可。

你的基本问题是你没有以关系格式存储数据,因为这个需求表明你有另一个实体。

+0

如果我使用Oracle,会怎么样? – Elmehdi93

+0

@ Elmehdi93。 。 。几乎相同的东西。存储数据的正确方法与您所从事的数据库密切相关(存在差异,但通常不在实体的定义中)。 –