What is the best constraint to use on a forum table where users leave comments?
Assuming some users will be deleted at a later stage. if i delete a user who has commented, what happens to the users entry in the table?
Hope someone can explain.
There are two parts to this question:
how best to implement this? You can "soft-delete" user rows. This has the advantages of:
Soft-deleting can be implemented by adding another column to the users table, with a dateDeleted
column -- if it's Null, then the user isn't deleted. I believe SO uses such a mechanism for deleting posts.
what does restrict cascade no action
do? The MySQL docs say
RESTRICT: Rejects the delete or update operation for the parent table. Specifying RESTRICT (or NO ACTION) is the same as omitting the ON DELETE or ON UPDATE clause.
NO ACTION: A keyword from standard SQL. In MySQL, equivalent to RESTRICT. InnoDB rejects the delete or update operation for the parent table if there is a related foreign key value in the referenced table. Some database systems have deferred checks, and NO ACTION is a deferred check. In MySQL, foreign key constraints are checked immediately, so NO ACTION is the same as RESTRICT.
In other words, if you use this, you won't be able delete rows if doing so would break referential integrity.
InnoDB
as your storage engine, foreign keys will automatically be enforced. So the defaults for ON UPDATE
and ON DELETE
are fine, since you won't (or at least, shouldn't) be changing the primary keys of rows - Matt Fenwick 2012-04-05 19:21