0

我有一个系统,其中包含与事件相关的类别。所有这些类别都很简单,它们有一个 ID 和名称。让我担心的一件事是,当我创建这些类别时,id 应该始终保持不变,是静态的。如果我删除了一个,比如说 id=1 的“政治”,那么所有这些事件都会有一个孤立的类别。我想到的一种解决方案是只为它们分配字符串 ID,因此如果它们碰巧被删除,那也没关系。你推荐什么样的解决方案?

从我的角度来看,您似乎可以保留 id 并设置一个不允许您删除记录的约束,只编辑它们。另一种是使用字符串 id,但这似乎很痛苦,尽管它似乎解决了担心 id 被弄乱的问题。

4

1 回答 1

0

Yes, this is what foreign key constraints are for. They also allow for rules on how to handle deletes -- for example, allowing a delete to cascade through dependent records, which is of course very dangerous and not what you would want in this situation. A simple basic constraint will do.

HOWEVER!!!! This is the important thing to understand about mysql. The default mysql engine (myisam) has absolutely no support for foreign key constraints. You need to use an engine that supports them -- most commonly innodb.

If you specify a constraint when you're generating your DDL, a myisam table will accept the constraint but simply ignore it, so make sure all your related tables are setup/altered to be innodb tables before you add your constraint(s).

How do you add a constraint?

ALTER TABLE `event` ADD CONSTRAINT `category_event` 
FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`);

In this example, it assumes your event table has the foreign key category_id in it, to create your linkage. After adding this constraint, if you attempt to delete a row from the category table, and an existing event row contains that key, mysql will disallow the DELETE and return an error. This is discussed in great detail here: http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html

于 2013-08-14T21:36:50.210 回答