I'm still learning how to create tables in MySQL and I'm having some difficulty. If it were to create a table with your relationship, it would create 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,
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 looks 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 command can be run in MySQL to add a foreign key?
FOREIGN KEY (codigo_estilo) REFERENCES estilo(codigo)