Question

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 (categories),
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;
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top