How to use Foreign key in SQL statements?

Asked

Viewed 250 times

1

I’m wanting to use Foreign key but I’m not getting it. This instruction SQL will create a table called tbl_estado with 4 columns id, nome, uf, pais and in the column pais will enter the key Foreign that will be searched in tbl_pais the id of the country which is the column id.

$where = axitech20 (bank)

$tablep = tbl_pais

$tableet = tbl_estado

inserir a descrição da imagem aqui

$sql8   = "CREATE TABLE IF NOT EXISTS $aonde.$tablee (
            id INT(6) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT PRIMARY KEY,
            nome        VARCHAR(75) DEFAULT NULL,
            uf          VARCHAR(5) DEFAULT NULL,
            pais        INT(6) DEFAULT NULL KEY '??????????' ($tablep)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=28";

I’m not getting to do the relationship that’s something in there ?????????? of the instruction. Can help me to hit the foreign key?

  • 2

    Have you tried to check on mysql documentation ?

  • I tried yes that’s how I managed to create the instruction but I’m not getting the instructions that go there ???????

  • 2

    FOREIGN KEY (product_category, product_id) REFERENCES product(category, id)

1 answer

3


That way it should work:

CREATE TABLE axitech20.tb1_pais (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT
);

CREATE TABLE axitech20.tbl_estado (
    id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    id_pais INT NOT NULL,
    nome VARCHAR(75),
    uf VARCHAR(5),
    FOREIGN KEY (id_pais) REFERENCES tb1_pais(id)
);
  • My doubt is precisely because of the prefix of the table name. You can apply this code taking into account the prefix tbl_ please. I already mark your answer as correct.

  • So it should work, any error let me know!

  • That one (id_pais) all right?

  • 1

    id_pais refers to the column of the table tbl_estado that will receive the id value of one of the tuples (rows) of the table tbl_pais. You can put another name if you want

Browser other questions tagged

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