1
I’m still learning how to create tables in Mysql and I’m having some difficulty. If you were to create a table with your relationship, you would create:
CREATE TABLE estilo (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE cerveja (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
sku VARCHAR(50) NOT NULL,
nome VARCHAR(80) NOT NULL,
descricao TEXT NOT NULL,
valor DECIMAL(10, 2) NOT NULL,
teor_alcoolico DECIMAL(10, 2) NOT NULL,
comissao DECIMAL(10, 2) NOT NULL,
sabor VARCHAR(50) NOT NULL,
origem VARCHAR(50) NOT NULL,
codigo_estilo BIGINT(20) NOT NULL,
FOREIGN KEY (codigo_estilo) REFERENCES estilo(codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
To know how to add a foreign key to my table, let’s assume my table is like this:
CREATE TABLE estilo (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
nome VARCHAR(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE cerveja (
codigo BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
sku VARCHAR(50) NOT NULL,
nome VARCHAR(80) NOT NULL,
descricao TEXT NOT NULL,
valor DECIMAL(10, 2) NOT NULL,
teor_alcoolico DECIMAL(10, 2) NOT NULL,
comissao DECIMAL(10, 2) NOT NULL,
sabor VARCHAR(50) NOT NULL,
origem VARCHAR(50) NOT NULL,
codigo_estilo BIGINT(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the command that can be run in Mysql to add a foreign key?
FOREIGN KEY (codigo_estilo) REFERENCES estilo(codigo)
How to add a Foreign key to an already created table
– rray
Still I’m having trouble understanding to apply in my case.
– wladyband
What is the difficulty? the syntax? of any error?
– rray