I try to add a foreign key on a table but whenever I try I always have this error
ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'total_ibfk_1' in the referenced table 'all_votes'
The table that is being created is this one (members is another table that has nothing to do with the error, so give no importance to it)
CREATE TABLE IF NOT EXISTS all_votes (
id_vote INT AUTO_INCREMENT PRIMARY KEY,
id_member INT,
name_member VARCHAR(20),
vote VARCHAR(20) NOT NULL,
type_of_vote VARCHAR(10) NOT NULL,
topic VARCHAR(20) NOT NULL,
FOREIGN KEY (id_member) REFERENCES members(id)
);
And this is the table that occur the error
CREATE TABLE IF NOT EXISTS total (
topic VARCHAR(20) PRIMARY KEY,
type_of_vote VARCHAR(10) NOT NULL,
counts INT NOT NULL,
FOREIGN KEY (topic) REFERENCES all_votes(topic)
);
I've read a ton of answers, but none of them seems to work for me. This answer was the most instructive that summarize more less every other one.
I guess the error has to do with the reference of a foreign key to a non-primary key. The thing is that a lot of people says it's possible, but I didn't find a single code example, so I probably messed up somewhere there.