MySQL - 将同一个表中的两个元素链接到另一个表中
我在 MySQL 中创建了一个表,我想在这些元素之间建立连接。
它应该是多对多关系,我想出的是以下内容:
创建一个包含元素的表:
餐桌药
<强>|编号 |名称 |描述 |
创建一个包含链接的表格:
表不兼容
<强>| Medicine_id_1 | Medicine_id_2 |
因此,当我想在药品 1 和药品 2 之间创建不兼容时,我应该这样做:
INSERT INTO incompatibilities VALUES 1,2
当我想检索所有与药品 ID = 1 不兼容的药品时,我应该这样做:
SELECT * FROM incompatibilities WHERE medicine_id_1=1 OR medicine_id_2=1
这是正确的做法是?这些查询是否按预期工作?有没有更有效的方法来完成我所追求的事情?
先感谢您
I have created a table in MySQL, and i would like to make connections between those elements.
It should be a many-to-many relationship, and what i've come up with is the following:
Create a table with the elements:
table Medicine
| id | name | description |
Create a table with the links:
table Incompatibilities
| medicine_id_1 | medicine_id_2 |
So when i want to create an incompatibility between medicine 1 and medicine 2, i should do:
INSERT INTO incompatibilities VALUES 1,2
And when i would like to retrieve all the medicine that are incompatible with medicine ID = 1 i should do:
SELECT * FROM incompatibilities WHERE medicine_id_1=1 OR medicine_id_2=1
Is this the correct way to do it? Are those queries work as intended? Is there a more efficient way to do what i am after?
thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于不相容性是一种对称非自反关系,因此您应始终按顺序存储药物:id 最小的药物在
medicine_id_1
中,id 最大的药物在medicine_id_2
中。您应该创建唯一索引:
,插入值:
这样,您就可以在单个记录中以两种方式存储关系,并且
UNIQUE
约束可以正常工作。要选择所有不相容的药物:
Since incompatibility is a symmetric irreflexive relationship, you should always store the medicines in order: that with a least id in
medicine_id_1
, that with the greatest id inmedicine_id_2
.You should create the unique indexes:
, insert the values:
This way, you store the relationships in both ways within a single record, and the
UNIQUE
constraints work properly.To select all incompatible medicines: