gpt4 book ai didi

MySQL 友谊模式

转载 作者:行者123 更新时间:2023-11-29 01:54:29 26 4
gpt4 key购买 nike

我有以下表格

create table users
(
id_user int(9) AUTO_INCREMENT primary key,
email varchar(64)
);

create table friendships
(
id_friendship int(9) AUTO_INCREMENT primary key,
id_friend1 int(9),
id_friend2 int(9),
FOREIGN KEY (id_friend1) REFERENCES users(id_user),
FOREIGN KEY (id_friend2) REFERENCES users(id_user),
UNIQUE(id_friend1,id_friend2)
)

我想避免两个用户之间有两次相同的友谊。但我仍然可以像这样插入相同的友谊两次:

INSERT INTO friendships( id_friend1, id_friend2) VALUES (1,2)
INSERT INTO friendships( id_friend1, id_friend2) VALUES (2,1)

对我来说 (1,2) 和 (2,1) 是相等的,我想避免它。我怎样才能实现它?

最佳答案

您可以按特定顺序编写这些 ID。例如,在插入之前,尽量确保较小的 id 进入左列,较大的 id 进入另一列。

在你的例子中总是这样:

INSERT INTO friendships( id_friend1, id_friend2) VALUES (1,2)

永远不要这样:

INSERT INTO friendships( id_friend1, id_friend2) VALUES (2,1)

因为 id 2 比 id 1 大。

希望对您有所帮助!

关于MySQL 友谊模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33018426/

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