开发者

Having trouble with foreign key

I am trying to have categories in my budget2000 table be the foreign key to category in mainBudget. Category is not a unique number so it cannot be a primary key. When I run the code I get the famous error 1005. When I make category part of the primary key in mainBudget with id the code runs, however this will create problems later on. What can I do to make categories a foreign key. I am using mysql 5.5.

Here is my code

create table mainBudget(
id  SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
year    Year NOT NULL,
amount  double(10,2) NOT NULL,
category SMALLINT UNSIGNED NOT NULL,
primary key(id)
)ENGINE=INNODB;



create table budget2000(
id  SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
categories  SMALLINT UNSIGNED NOT NULL,
INDEX categoryNumber (cate开发者_如何学运维gories),
subCategory SMALLINT NOT NULL,
amount   FLOAT(10,2) NOT NULL,
date    DATE NOT NULL,
description VARCHAR(300) NOT NULL,
primary key(id),
FOREIGN KEY (categories) REFERENCES mainBudget(category)
)ENGINE=INNODB;


category is not indexed in mainBudget. The column in the referenced table has to be indexed (or the left prefix of an index).

Incidentally, are you sure it isn't better to have an additional table category and have mainBudget.category and budget200.categories both foreign keys to this table? Your current setup looks a little odd, particularly with the referenced column in mainBudget not being unique.


Having FKs referencing non-unique columns is not standard SQL. Even when MySQL InnoDB allows this, it does not mean that it is a good idea.

Make some ER-Diagrams and normalize your tables. (Use 3.NF if nothing else forces you not to do.) Having a separate table for Category seems to be the way to go. On the other hand the naming of your exiting tables makes me thinking these should be only one table or their naming is bad.

And when this 2000 has something to do with a year or what then forget about it. You can select this easy in your Queries. Just put everything in one table no matter what year it is.

Your question/problem seems to be design-related to me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜