How can I not register a foreign key?

0

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

  • Voter ( Pk titulodeeleior, name)
  • Feedback ( Fk titulodeeleitor, vote)
To my knowledge, the VotosComputados table should not insert a FK any, but one that already exists in the Eleitor table, however I am making a INSERT and it is inserting a FK any.

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 Eleitor table.

Below is 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);
    
asked by anonymous 22.10.2017 / 03:21

1 answer

1

First, a primary key can not be VARCHAR (as far as I know). I would advise you to create another id field, for example, of integer type, and use it as the primary key of the Eleitor table. And for the foreign key you must use an integer as well. In this 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;
    
22.10.2017 / 03:38