MySQL列取决于另一列

时间:2017-05-21 13:29:30

标签: mysql

我在MySQL中有一个像这样的表

ID  |  Attribute1  |  Attribute2
--- | ------------ | ------------
15  |  value1      | value2

然后我有另一张这样的表:

ID  |  Attribute  
--- | ------------ 
15  |  value1
15  |  value2

有没有办法让表1中的Attribute1只能在另一个表的相应值中选择?

让我们举个例子:

ID          |  Attribute
----------- |  -----------
 Apple      |  Red
 Apple      |  Yellow
 BlueBerry  |  Red
 BlueBerry  |  Blue

ID         |  Attribute1
---------------------------
Apple      |   Red
BlueBerry  |   Blue

我不想选择" blue"对于" Apple"。

1 个答案:

答案 0 :(得分:0)

您可以添加约束:

ALTER TABLE table1 ADD CONSTRAINT fk_t1_attr1 FOREIGN KEY (id, attribute1)
                                              REFERENCES table2 (id, attribute);

因此,您只能输入table1中存在的id / attribute对。