How can I not let you register any foreign key?

Asked

Viewed 47 times

0

I have a database of an electronic urn with the following tables:

  • Voter(Pk title )
  • Votoscomputers(Fk quibbler , vote)

To my knowledge, the table VotosComputados should not insert a FK any, and yes one that already exists in the table Eleitor, but I’m making a INSERT and he’s inserting a FK whichever.

In short:

When I make a INSERT in the table that has the foreign key, it is letting me insert a key that is not registered in the table Eleitor.

Below follows how I created my tables:

CREATE TABLE Eleitor(
titulodeeleitor VARCHAR(150) ,
nome VARCHAR(30) NOT NULL ,
primary key (titulodeeleitor)
);
create table votoscomputados(
titulodeeleitor varchar(150),
votoinserido int 
);
alter table votoscomputados add foreign key (titulodeeleitor) references Eleitor(titulodeeleitor);

1 answer

1

First, a primary key cannot be VARCHAR (as far as I know). I advise you to create another field id, for example, integer type, and use it as table primary key Eleitor. And for the foreign key you should use a whole too. In case, it would look like this:

CREATE TABLE `eleitor` (
  `id` int(11) NOT NULL,
  `titulodeeleitor` varchar(150) DEFAULT NULL,
  `nome` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `votoscomputados` (
  `id` int(11) NOT NULL,
  `votoinserido` int(11) NOT NULL,
  `eleitor` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `eleitor`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `votoscomputados`
  ADD PRIMARY KEY (`id`),
  ADD KEY `eleitor` (`eleitor`);

ALTER TABLE `eleitor`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

ALTER TABLE `votoscomputados`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

ALTER TABLE `votoscomputados`
  ADD CONSTRAINT `votoscomputados_ibfk_1` FOREIGN KEY (`eleitor`) REFERENCES `eleitor` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.