SQL to create fk int in TABLE

Asked

Viewed 82 times

-4

  1. Film
  2. COD (int, pk)
  3. name(varchar 20, not null)
  4. birth (datetime, not null)
  5. Obs(tinybit, not null)
  6. Obs2(int, fk, not null)

I thought of something like

create table filme (
COD int PRIMARY KEY AUTO_INCREMENT,
nome varchar(200) NOT NULL,
nascimento datetime NOT NULL,
obs tinyint NOT NULL,
obs2 int NOT NULL

)

I can’t create fk...

how do I create a fk int?

1 answer

1


you can do so:

create table filme (
COD int NOT NULL AUTO_INCREMENT,
nome varchar(200) NOT NULL,
nascimento datetime NOT NULL,
obs tinyint NOT NULL,
obs2 int NOT NULL
PRIMARY KEY (COD),
FOREIGN KEY (obs2) REFERENCES OutraTabela(ColunaChave)
);

if you have already created the table can add a foreign FK key like this:

ALTER TABLE `filme ` ADD CONSTRAINT `fk_filme` FOREIGN KEY ( `obs2` ) REFERENCES `OutraTabela` ( `ColunaChave` ) ;
  • Thank you! helped me a lot.... but I have another problem I can not add anything in the line when you have a fk, for example if you have fk in Obs2 I can not add anything in the table, you know tell me pq? (I’m learning sql now)

  • @Jolegendary, as the problem was solved in this answer, it is ideal for you to mark it as accepted and create a new question. Read at that link

Browser other questions tagged

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