[英]Insert but only if a condition on another table is met
I have 3 tables for a messaging system我有 3 个用于消息传递系统的表
Conversations对话
| id |
Participants参与者
| id | conversation | user |
Messages留言
| id | conversation | user | text |
I want to restrict messages being inserted into a conversation if the user is not part of through the participants table如果用户不是参与者表的一部分,我想限制将消息插入对话
I think I could structure it in a better way by having participant in the messages table.我认为我可以通过让参与者参与消息表来以更好的方式构建它。 But then id have to do an extra query by seeing what a users participant id is before inserting a message.
但是在插入消息之前,id 必须通过查看用户参与者 id 来做一个额外的查询。
Id rather do it with a constraint or foreign key.我宁愿用约束或外键来做。 What would the best way to do this be?
最好的方法是什么?
You can use EXISTS
in the INSERT
statement:您可以在
INSERT
语句中使用EXISTS
:
INSERT INTO Messages(id, conversation, user, text)
SELECT :id, :conversation, :user, :text
FROM dual
WHERE EXISTS (
SELECT 1
FROM Participants
WHERE conversation = :conversation AND user = :user
)
If your version of MySql is 8.0+ you can omit FROM DUAL
.如果您的 MySql 版本是 8.0+,您可以省略
FROM DUAL
。
Replace :id
, :conversation
, :user
and :text
with the column values that you want to insert.将
:id
、 :conversation
、 :user
和:text
替换为要插入的列值。
If ID
is an autoincremented integer change to:如果
ID
是自动递增的 integer 更改为:
INSERT INTO Messages(conversation, user, text)
SELECT :conversation, :user, :text
................................
Or, first create a UNIQUE
constraint for the combination of columns conversation
and user
in Participants
:或者,首先为
Participants
中的conversation
和user
列的组合创建一个UNIQUE
约束:
ALTER TABLE Participants ADD CONSTRAINT unique_conv_user UNIQUE (conversation, user)
and then add a foreign key constraint for the combination of columns conversation
and user
in Messages
:然后为
Messages
中的conversation
和user
列的组合添加外键约束:
ALTER TABLE Messages
ADD CONSTRAINT fk_conv_user
FOREIGN KEY (conversation, user) REFERENCES Participants(conversation, user);
This way you can only insert new rows in Messages
if the combination of conversation
and user
already exists in Participants
.这样,如果
conversation
和user
的组合已经存在于Participants
中,您只能在Messages
中插入新行。
Is this a trick question?这是一个技巧问题吗? You just described the main use case of referential integrity in a data base.
您刚刚描述了数据库中参照完整性的主要用例。 Make Messages.(ID, User) a foreign key of the Participants table.
使 Messages.(ID, User) 成为 Participants 表的外键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.