gpt4 book ai didi

mysql - 有意义 N :M relationship with foreign and primary keys?

转载 作者:行者123 更新时间:2023-11-29 12:23:39 25 4
gpt4 key购买 nike

我有一个 CONSUMER 实体和一个 DEVICE 实体。 CONSUMER 和 DEVICE 之间存在 N:M 关系 CONECTION。

我有来自 CONSUMER 的外键 CONSUMER_EMAIL 和来自 DEVICE 的 DEVICE_INDEX_ID。 CONECTION 有时间属性。

生成 token 并将其发送给用户,以便对用户进行身份验证以请求数据。

拥有这两个外键并且还有一个允许将每个设备区分为唯一键的 (device_index_id, time) 是否有意义?表格草图:

-------------------------------------------------------------
-- User [conects from] device relationship N:M ----------
CREATE TABLE conection (
token CHAR(64) NOT NULL, -- Randomly generated and sent to the user
consumer_email VARCHAR(254) NOT NULL,
device_index_id UNSIGNED MEDIUMINT NOT NULL,
time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (consumer_email)
FOREIGN KEY (device_index_id)
UNIQUE KEY (device_index_id, time)
PRIMARY KEY (token)
) ENGINE=InnoDB;

最佳答案

N:M 关系表很简单

CREATE TABLE ConsumerDevice (
consumer_email ... -- PRIMARY KEY for Consumer
device_index_id ... -- PRIMARY KEY for Device
PRIMARY KEY(consumer_email, device_index_id) -- for going one way
INDEX( device_index_id, consumer_email) -- for going the other direction
) ENGINE=InnoDB;

是的,您可以添加

time TIMESTAMP NOT NULL

甚至可以默认更新到当前时间。您的 token 是不必要的。对于给定的消费者-设备对,不应有多个行。2 外键应该是显而易见的,但为什么要这么麻烦呢?

使用 INSERT...ON DUPLICATE KEY UPDATE... 创建新行或一步更新时间

关于mysql - 有意义 N :M relationship with foreign and primary keys?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28657074/

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