主键、外键和唯一约束的实际工作及其工作顺序/步骤
主键、外键和唯一约束如何工作?我的意思是按什么顺序?
例如,当子表有 FK 时,向其中插入一条记录,而该记录在父表中不存在,则该记录首先插入到子表中,然后再将其插入到子表中。然后约束在父表中检查该记录是否存在,如果没有找到,则回滚并从子表中删除该记录。这是工作顺序吗?
或者,第一个 SQL 是否从插入查询中获取记录(在其上进行 FK),&与父表记录匹配,并在没有找到匹配记录时停止插入,而插入本身并不在子表中插入该行?
同样,对于主键,如果表中插入了重复记录,那么是先插入再检查还是插入前先与现有记录进行匹配,如果是重复则停止查询。
How do primary key , foreign key and unique constraints work? i mean in what sequence?
Like, when a child table has a FK, and a record is inserted into it , which doesn't exists in the parent table, then is this record first inserted into the child table & then the constraint checks in the Parent table if this record exists or not, and if it doesn't finds it then it rollbacks and removes the record from the Child table. is this the order of working?
or, does first SQL gets the record(on which the FK is made) from the insert query, & matches it with the parent table records, and ceases the insert when matching record is not found, while insertion itself and doesn't inserts the row in the child table?
Similarly, for the primary key, if a duplicate record is inserted in a table, then is it first inserted then checked or before insertion first it is matched with existing records, and if it is a duplicate one, then the query is ceased.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从逻辑上讲,应该根据 UPDATE、INSERT 或 DELETE 语句的整个结果同时检查所有约束。对约束进行评估,就好像对所有行的修改都已发生一样,如果违反任何约束,则不允许进行修改。
Logically speaking, all constraints are supposed to be checked simultaneously against the entire result of an UPDATE, INSERT or DELETE statement. The constraints are evaluated as if the modification to all rows had already happened and if any constraint would be violated then the modification is not permitted.
您需要 RDBMS 参考的基础知识。这是免费资源: http://msdn .microsoft.com/en-us/library/aa933098%28v=SQL.80%29.aspx
You need the basic of rdbms reference. Here is the free resource: http://msdn.microsoft.com/en-us/library/aa933098%28v=SQL.80%29.aspx
考虑可
触发
。即使这些也只是概念。谁知道幕后发生了什么? ...好吧,肯定有人知道...但是您关心幕后发生了什么吗?在概念层面上,它要么成功,要么失败,或者您可以在触发器中操纵结果。您还需要了解什么? ;)Consider the logical (conceptual) tables
deleted
andinserted
that are accessible to aTRIGGER
. Even these are only concepts. Who knows what's going on under the covers? ...well, someone is bound to know... but do you care what's going on under the covers? At the conceptual level, it either succeeds or fails or you can manipulate the outcome in a trigger. What more do you need to know? ;)