简体   繁体   English

Mysql如何创建EQUAL约束?

[英]Mysql how to create EQUAL constraint?

Is there a way to create an "EQUAL" constraint in Mysql?有没有办法在 Mysql 中创建“EQUAL”约束?

Imagine I have a table like this想象我有一张这样的桌子

tb_1:

id | id_fk | order | id_tb_2 | Column D
----------------------------------------
1  | 1     | 1     | 10      | AAA
2  | 1     | 2     | 20      | BBB
3  | 2     | 1     | 30      | CCC
4  | 3     | 1     | 40      | DDD

And:和:

tb_2:

id_tb_2 | id_type
------------------
10      | 100
20      | 200
30      | 300
40      | 400

And:和:

tb_3:

id_type | model    | other_prop
--------------------------------
100     | model_A  | A
200     | model_A  | B
300     | model_B  | C
400     | model_C  | D

I want to make sure that tb_2.id_type.model are going to be equal for same values of id_fk and different order .我想确保tb_2.id_type.model对于id_fk相同值和不同的order将是相等的。

So I have a UNIQUE constraint for [id_fk, order]所以我有一个[id_fk, order]UNIQUE约束

And I need a EQUAL constraint for [id_fk, id_tb_2.id_type.model]我需要一个[id_fk, id_tb_2.id_type.model]EQUAL约束

This way, I shouldn't be able to create a value in tb_1 like:这样,我不应该能够在tb_1创建一个值,例如:

id | id_fk | order | id_tb_2 | Column D
----------------------------------------
1  | 1     | 1     | 10      | AAA
2  | 1     | 2     | 20      | BBB
5  | 1     | 3     | 30      | EEE  <--- This has a different model in tb_2

How can I create one?我怎样才能创建一个?

A solution using proper relational normalization is to drop the tb_1.Column D column.使用适当关系规范化的解决方案是删除tb_1.Column D列。

Then the reference to tb_2.id_tb_2 and by extension to tb_3.id_type will be unambiguous.然后,参照tb_2.id_tb_2并延伸到tb_3.id_type将是明确的。

tb_1:

id | id_fk | order | id_tb_2
----------------------------
1  | 1     | 1     | 10
2  | 1     | 2     | 20
3  | 2     | 1     | 30
4  | 3     | 1     | 40

In other words, by including Column D in tb_1, you're violating Third Normal Form , because Column D is an attribute that depends on something other than the primary key of tb_1.换句话说,通过在 tb_1 中包含 D 列,您违反了第三范式,因为 D 列是一个依赖于 tb_1 主键以外的其他内容的属性。

But I'm not sure you've told us the full scope of the problem you're trying to solve.但我不确定您是否已告诉我们您试图解决的问题的全部范围。

You can't.你不能。

The only constraints that relate data from multiple tables are FOREIGN KEY constraints;与来自多个表的数据相关的唯一约束是FOREIGN KEY约束; and they are very limited about the relationship they check: a list of columns against another list of columns on another/same table.并且他们对他们检查的关系非常有限:一个列列表与另一个/同一个表上的另一个列列表。

All other relational constraints (such as UNIQUE or CHECK ) have a table scope.所有其他关系约束(例如UNIQUECHECK )都有一个表范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM