基于另一列的列约束
Constraint on a column based on another column
我有一个 table "Table",其中包含一个 ID,Col1 和 Col2,Col3。
Col2 可以是 0 或 1。
我希望 Col1 具有相同值的行中的 Col2 相同。
例如
我想要这样的东西
+----+-------+------+-----------+
| 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" )
+----+-------+------+-----------+
即使 MySQL 支持检查约束,您也不会使用 check
约束来执行此操作。我认为最好的方法是使用外键约束。
您需要第二个 table 具有有效的 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
);
那么您的 table 将是:
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)
);
但是,我什至不会将 col2
存储在 t
中。而是从 t
中删除它,然后只查找 col1col2
.
中的值
你的基本问题是你没有以关系格式存储数据,因为这个要求表明你有另一个实体。
我有一个 table "Table",其中包含一个 ID,Col1 和 Col2,Col3。 Col2 可以是 0 或 1。 我希望 Col1 具有相同值的行中的 Col2 相同。 例如
我想要这样的东西
+----+-------+------+-----------+
| 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" )
+----+-------+------+-----------+
即使 MySQL 支持检查约束,您也不会使用 check
约束来执行此操作。我认为最好的方法是使用外键约束。
您需要第二个 table 具有有效的 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
);
那么您的 table 将是:
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)
);
但是,我什至不会将 col2
存储在 t
中。而是从 t
中删除它,然后只查找 col1col2
.
你的基本问题是你没有以关系格式存储数据,因为这个要求表明你有另一个实体。