Setting up table relations what do “Cascade”, “Set Null” and “Restrict” do?

巧了我就是萌 提交于 2019-11-26 18:52:59

问题


I want to start using table relations in a new project.

After some googling I got 2 tables set up as InnoDB:

The keys I want to link are

->users->userid (primary) ->sessions->userid (index)

The only thing that I don't understand in this process is what the different settings for "On update" and "On delete" do

The options here are:

  • -- (nothing?)
  • Cascade (???)
  • Set Null (sets everything to null?)
  • No action (well duh...)
  • Restrict (???)

I basically want the data in sessions to be deleted when a user is completely deleted This since the sessions will only be deleted when the expiration is detected by my session manager...

So if anyone can tell me what these options do it would be much appreciated.


回答1:


CASCADE will propagate the change when the parent changes. (If you delete a row, rows in constrained tables that reference that row will also be deleted, etc.)

SET NULL sets the column value to NULL when a parent row goes away.

RESTRICT causes the attempted DELETE of a parent row to fail.

EDIT: You didn't ask about them, but the SQL standard defines two other actions: SET DEFAULT and NO ACTION. In MySQL, NO ACTION is equivalent to RESTRICT. (In some DBMSs, NO ACTION is a deferred check, but in MySQL all checks are immediate.) The MySQL parser accepts SET DEFAULT, but both the InnoDB and NDB engines reject those statements, so SET DEFAULT can't actually be used for either an ON UPDATE or ON DELETE constraint.

Also, note that cascading foreign key actions do not activate triggers in MySQL.




回答2:


The table containing the foreign key is called the referencing or child table, and the table containing the candidate key is called the referenced or parent table.

Set NULL : Sets the column value to NULL when you delete the parent table row.

CASCADE : CASCADE will propagate the change when the parent changes. If you delete a row, rows in constrained tables that reference that row will also be deleted, etc.

RESTRICT : RESTRICT causes you can not delete a given parent row if a child row exists that references the value for that parent row.

NO ACTION : NO ACTION and RESTRICT are very much alike. when an UPDATE or DELETE statement is executed on the referenced table, the DBMS verifies at the end of the statement execution that none of the referential relationships are violated. in short child row no concern if parent row delete or update.



来源:https://stackoverflow.com/questions/5383612/setting-up-table-relations-what-do-cascade-set-null-and-restrict-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!