gpt4 book ai didi

mysql - 如何避免在多对多关系中使用相同的 ID

转载 作者:可可西里 更新时间:2023-11-01 08:44:56 24 4
gpt4 key购买 nike

foo_bars 是一个多对多表,两列都指向 foo.id我想要 foo_bars.[id1, id] 来获取唯一键如何避免在 foo_bars 条目中使用相同的 ID。

即插入 foo_bars (2,2) - 如何避免这种情况?

mysql> create table foo (id int(11), name varchar(255));
Query OK, 0 rows affected (0.49 sec)

mysql> desc foo;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> create table foo_bars (id1 int(11), id int(11));
Query OK, 0 rows affected (0.34 sec)

mysql> desc foo_bars;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id1 | int(11) | YES | | NULL | |
| id | int(11) | YES | | NULL | |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

最佳答案

你可以添加一个独特的contatraint

CHECK (id1<>id)

create table foo_bars (id1 int(11), id int(11),CHECK (id1<>id));

关于mysql - 如何避免在多对多关系中使用相同的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31534144/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com