MySQL Phone 表:如何为每个 ID 指定唯一的主要联系人号码?
我的表格如下:
CREATE TABLE IF NOT EXISTS PHONES (
number VARCHAR(10),
id INT,
type VARCHAR(10),
PRIMARY KEY (number),
FOREIGN KEY (id)
REFERENCES TECHNICIANS(id)
ON DELETE CASCADE
) ENGINE = INNODB;
我想为每个 id 指定一个主要联系号码。我正在考虑添加一个布尔列,但我不知道如何让它只允许一个“真”值。 ID。
My table is as follows:
CREATE TABLE IF NOT EXISTS PHONES (
number VARCHAR(10),
id INT,
type VARCHAR(10),
PRIMARY KEY (number),
FOREIGN KEY (id)
REFERENCES TECHNICIANS(id)
ON DELETE CASCADE
) ENGINE = INNODB;
I would like to specify for each id one primary contact number. I was thinking of adding a boolean column, but I can't figure out how to get it to only allow one "true" value per. id.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会将技术人员的外键添加回电话:
这将创建一个循环引用:技术人员引用电话,电话引用技术人员。这没问题,但是当您执行删除表、恢复备份等操作时,需要特殊处理。
I'd add a foreign key from TECHNICIANS back to PHONES:
This creates a cyclical reference: technicians references phones, and phones references technicians. This is okay, but it requires special handling when you do things like dropping tables, restoring backups, etc.
利用MySQL中的“漏洞”。 MySQL文档说:
这意味着您可以创建一个具有两个值的布尔列:true(或 1)和 NULL。
在该列+您的键上创建一个唯一索引。这允许您仅将一条记录设置为 true,但任意数量的记录都可以为 NULL。
Use a "loophole" in MySQL. The MySQL documentation says:
This means that you can create a boolean column that has two values: true (or 1) and NULL.
Create a UNIQUE index over that column + your key. That allows you to only set one record to true, but any number of them can have NULL.
你基本上有3个选项......
顺便说一句,我假设您实际上是指每个 TechnicianId 而不是每个 PhoneId 一个主要号码
You've basically got 3 options...
Incidentally, I'm assuming you actually mean one primary number per TechnicianId not per PhoneId