how to retrieve foreign key linked to a certain primary key - mysql

I have a simple MySQL DB with a table which has PK composed by 2 varchar columns.
CREATE TABLE prodotti(
type_prod varchar(10) not null,
model_prod varchar(10) not null,
brand_prod varchar(20) not null,
name_prod varchar(30) not null,
year_prod int not null,
description_prod varchar(500) not null,
price_prod float not null,
qnt_prod int not null,
PRIMARY KEY(type_prod,model_prod) );
There are also other table with FKs linked to this PK (in this case,I show you just 2 of these tables)
CREATE TABLE cpu_component(
id_cpu varchar(10) not null,
series_cpu varchar(20) not null,
num_cores int not null,
frequency_ghz int not null,
socket_cpu int not null,
label_cpu varchar(10),
model_cpu varchar(10),
PRIMARY KEY (id_cpu),
FOREIGN KEY(label_cpu,model_cpu) REFERENCES prodotti(type_prod,model_prod)
ON UPDATE CASCADE
ON DELETE CASCADE );
CREATE TABLE motherboard_component(
id_motherboard varchar(10) not null,
series_motherboard varchar(20) not null,
chipset_motherboard varchar(15) not null,
socket_motherboard int not null,
type_ram_motherboard varchar(15) not null,
ram_frequency_index int not null,
slot_ram int not null,
hdmi_ports_gpu int not null,
usb_ports_motherboard int not null,
bios_motherboard varchar(10) not null,
label_motherboard varchar(10),
model_motherboard varchar(10),
PRIMARY KEY (id_motherboard),
FOREIGN KEY(label_motherboard,model_motherboard) REFERENCES prodotti(type_prod,model_prod)
ON UPDATE CASCADE
ON DELETE CASCADE );
I want to retrieve all FKs linked to a specific PK obtained by user input
P.S this is my first question here, please be clement lol

You can use SQL's INNER JOIN statements to achieve this in which joining the tables prodotti and cpu_component will give you all the rows from cpu_component that are also in prodotti.
SELECT p.type_prod, p.model_prod, cpu.num_cores
FROM prodotti p
INNER JOIN cpu_component cpu ON(cpu.label_cpu = p.type_prod AND cpu.model_cpu = model_prod)
As for joining the table prodotti with the table motherboard_component:
SELECT p.type_prod, p.model_prod, mc.chipset_motherboard
FROM prodotti p
INNER JOIN motherboard_component mc ON(mc.label_motherboard = p.type_prod AND mc.model_motherboard = p.model_prod)

Related

Error Code 1824 - Failed to open the referenced table

I'm trying to create my DB project on MySQL, and when I tried to add foreign keys, it show the error code 1824 on all of the tables I'm trying to create. My code is this:
create table cliente (
id_cliente varchar(20) not null primary key,
nome varchar(50) unique not null,
endereco varchar(70) not null,
celular varchar(15) not null,
id_cartao_cliente int not null,
cod_encomenda_cliente int not null,
constraint fk_cartao foreign key (id_cartao_cliente) references cartao_credito(id_cartao),
constraint fk_encomenda foreign key (cod_encomenda_cliente) references encomenda(cod_encomenda)
) engine = innodb;
create table cartao_credito (
id_cartao int not null primary key,
num_cartao varchar(20) not null,
nome_cartao varchar(30) not null,
mes_validade varchar(2) not null,
ano_validade year,
id_cliente_cartao varchar(20) not null,
constraint fk_cliente foreign key (id_cliente_cartao) references cliente(id_cliente)
) engine = innodb;
create table Encomenda (
cod_encomenda int not null primary key,
tipo varchar(15) not null,
valor_encomenda varchar(10) not null,
local_destino varchar(20) not null,
id_destinatario_encomenda varchar(20) not null,
constraint fk_destinatario foreign key (id_destinatario_encomenda) references destinatario(id_destinatario)
) engine = innodb;
create table movimentacao (
id varchar(50) not null primary key,
local_movimentacao varchar(50) not null,
descricao varchar(30) not null,
data_movimentacao date not null,
hora_movimentacao time not null,
cod_encomenda_movimentacao int not null,
id_entregador_movimentacao varchar(20) not null,
foreign key (cod_encomenda_movimentacao) references encomenda(cod_encomenda),
foreign key (id_entregador_movimentacao) references entregador(id_entregador)
) engine = innodb;
create table entregador (
id_entregador varchar(20) not null primary key,
nome varchar(50) unique not null,
placa_veiculo varchar(10) not null,
tipo_veiculo varchar(15) not null,
cod_encomenda_entregador varchar(50) not null,
id_destinatario_entregador varchar(20) not null,
foreign key (cod_encomenda_entregador) references encomenda(cod_encomenda),
foreign key (id_destinatario_entregador) references destinatario(id_destinatario)
) engine = innodb;
create table destinatario (
id_destinatario varchar(20) not null primary key,
nome varchar(50) not null unique not null,
endereco varchar(70) not null,
celular varchar(15) not null,
cod_encomenda_destinatario int not null,
foreign key (cod_encomenda_destinatario) references encomenda(cod_encomenda)
) engine = innodb;
I need help with this code please.
P.S.: all of the columns are written in Portuguese
MySQL error code 1824 is "Failure to open referenced table."
I believe you are running into trouble because of the order you are creating in. I see that "Encomenda" does not have a foreign key, and may be a good place to start your creation.
Your design is wrong. Because when an entity in cliente refer to cartao_credito it means there is a (1 to N) relation between these two table. So no need to refer cartao_credito to cliente again. If you need an N to N relationship use a bridge (a new table) between them and use two 1 to N relationship.
In your design all tables refer to each other mutually. For example in two first table you need just one foreign key to join these two tables not two foreign key.

How to ER Diagram MYSQL

I'm trying to create simple library database in mysql. I have 5 tables students, entry, book, typebook, author. When I was trying to make er diagram with mysql reverse engineer my tables doesn't have any relationships on er diagram. But almost every databases have relationships on er diagram in the internet. What am i doing wrong and how to fix it?
CREATE TABLE student(
`stuNo` INT NOT NULL,
`stuname` VARCHAR(45) NULL,
`stusurname` VARCHAR(45) NULL,
`class` INT NULL,
`age` INT NULL,
PRIMARY KEY (`stuNo`));
CREATE TABLE entry(
`stuNo` INT NOT NULL,
`entryno` INT NOT NULL,
`bookno` INT NOT NULL,
`borrowdate` DATE NULL,
`returndate` DATE NULL,
PRIMARY KEY (`bookno`));
CREATE TABLE book(
`bookno` INT NOT NULL,
`bookname` VARCHAR(45) NULL,
`authorno` INT NOT NULL,
`typeno` INT NOT NULL,
PRIMARY KEY (authorno , typeno));
CREATE TABLE typebook (
`typeno` INT NOT NULL,
`typename` VARCHAR(45) NULL,
PRIMARY KEY (`typeno`));
CREATE TABLE author(
`authorno` INT NOT NULL,
`authorname` VARCHAR(45) NULL,
`autorname` VARCHAR(45) NULL,
PRIMARY KEY (`authorno`));
I had to switch the order of the CREATE TABLE
What changes is the order you have to insert data.
For example
If you want to INSERT a book , you first have to insert the typebook and author, that corresponds to the book and so on.
CREATE TABLE student(
`stuNo` INT NOT NULL,
`stuname` VARCHAR(45) NULL,
`stusurname` VARCHAR(45) NULL,
`class` INT NULL,
`age` INT NULL,
PRIMARY KEY (`stuNo`));
CREATE TABLE typebook (
`typeno` INT NOT NULL,
`typename` VARCHAR(45) NULL,
PRIMARY KEY (`typeno`));
CREATE TABLE author(
`authorno` INT NOT NULL,
`authorname` VARCHAR(45) NULL,
`autorname` VARCHAR(45) NULL,
PRIMARY KEY (`authorno`));
CREATE TABLE book(
`bookno` INT NOT NULL,
`bookname` VARCHAR(45) NULL,
`authorno` INT NOT NULL,
`typeno` INT NOT NULL,
PRIMARY KEY (authorno , typeno),
INDEX(bookno),
FOREIGN KEY (typeno)
REFERENCES typebook(typeno),
FOREIGN KEY (authorno)
REFERENCES author(authorno));
CREATE TABLE entry(
`stuNo` INT NOT NULL,
`entryno` INT NOT NULL,
`bookno` INT NOT NULL,
`borrowdate` DATE NULL,
`returndate` DATE NULL,
PRIMARY KEY (`bookno`),
FOREIGN KEY (stuNo)
REFERENCES student(stuNo),
FOREIGN KEY (bookno)
REFERENCES book(bookno)
);
Results in
The problem is that your tables do not have any FOREIGN KEYS set. MySQL has no idea that the authorno column from one table should be linked to the authorno column from another table. So no relationship links are generated.
To generate the relationship links to your ER diagram, you have to use FOREIGN KEY entries in your CREATE TABLE query to specify which column from one table is referencing a column from a different table:
CREATE TABLE author(
`authorno` INT NOT NULL,
`authorname` VARCHAR(45) NULL,
`autorname` VARCHAR(45) NULL,
PRIMARY KEY (`authorno`)
);
CREATE TABLE book(
`bookno` INT NOT NULL,
`bookname` VARCHAR(45) NULL,
`authorno` INT NOT NULL,
`typeno` INT NOT NULL,
PRIMARY KEY (bookno),
FOREIGN KEY (authorno) REFERENCES author(authorno)
);
With the added FOREIGN KEY entries MySQL now knows that the authorno column in book must reference a value from the authorno column of the author table. When generating the ER diagram you should get the lines between the tables to see the relationship.

Can't figure out why mySql database syntax won't compile

I'm getting this syntax error for a DB I am writing for my own personal project and am unsure why this error is occuring, any help would be much appreciated! The desired result is just compilation at this point, and the error is a simple syntax error.
The problem table is the Team table.
Error Code: 1215: Cannot add foreign key contraint.
-- CREATE DATABASE basketBall;
DROP TABLE LEAGUE;
-- DROP TABLE TEAM;
DROP TABLE SESSION;
CREATE TABLE LEAGUE (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL UNIQUE,
PRIMARY KEY(id)
);
CREATE TABLE SESSION (
year INT NOT NULL,
season VARCHAR(50) NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(year, season, division),
CONSTRAINT chk_season CHECK (season IN ('Fall', 'Winter', 'Spring', 'Summer'))
);
CREATE TABLE TEAM (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
season VARCHAR(50) NOT NULL,
year INT NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY(season) REFERENCES SESSION(season),
FOREIGN KEY(year) REFERENCES SESSION(year),
FOREIGN KEY(division) REFERENCES SESSION(division)
);
CREATE TABLE PLAYER (
id INT NOT NULL AUTO_INCREMENT,
fname VARCHAR(30) NOT NULL,
lname VARCHAR(30) NOT NULL,
lid INT,
PRIMARY KEY(id)
);
CREATE TABLE GAME (
id INT NOT NULL AUTO_INCREMENT,
time VARCHAR(5),
court VARCHAR(20),
date DATE,
PRIMARY KEY(id)
);
CREATE TABLE STATS (
pid INT NOT NULL,
gid int NOT NULL,
pts INT NOT NULL,
fgm INT NOT NULL,
fga INT NOT NULL,
fta INT NOT NULL,
ftm INT NOT NULL,
3fgm INT NOT NULL,
3fga INT NOT NULL,
oreb INT NOT NULL,
dreb INT NOT NULL,
ast INT NOT NULL,
stl INT NOT NULL,
blk INT NOT NULL,
turnover INT NOT NULL,
eff INT NOT NULL,
pf INT NOT NULL,
min INT NOT NULL,
PRIMARY KEY(pid, gid),
FOREIGN KEY(pid) REFERENCES PLAYER(id),
FOREIGN KEY(gid) REFERENCES GAME(id)
);
CREATE TABLE Players_on_Team (
tid INT NOT NULL,
pid INT NOT NULL,
PRIMARY KEY(tid, pid),
FOREIGN KEY(tid) REFERENCES TEAM(id)
);
CREATE TABLE League_Sessions (
lid INT NOT NULL,
year INT NOT NULL,
season VARCHAR(50) NOT NULL,
division VARCHAR(5) NOT NULL,
PRIMARY KEY(lid, year, season, division),
FOREIGN KEY(lid) REFERENCES LEAGUE(id)
);
A column that you reference in a foreign key must be indexed. These two foreign keys in TEAM:
FOREIGN KEY(season) REFERENCES SESSION(season),
FOREIGN KEY(division) REFERENCES SESSION(division)
refer to columns that don't have indexes of their own. They're parts of a multi-column index, but only a prefix of a multi-column index acts as an index on those specific columns.
You could add separate indexes on the season and division columns to the SESSION table. But it would probably be more appropriate to make a multi-column foreign key:
FOREIGN KEY (year, season, division) REFERENCES SESSION(year, season, division)
I just tried it and it executes without any errors.

Foreign Keys in MySQL Workbench not working?

I am reverse engineering a database in MySQL Workbench but it doesn't seem to be importing or recognising the foreign keys. Which means I cant get it to draw the relationships.
While I am trying to get this to work I am using a snippet of a couple of tables, so its nothing complex.
Here are the 2 demo tables that I am trying to get to work:
CREATE TABLE users (
UserID varchar(32) NOT NULL,
OrgID varchar(6) NOT NULL,
RegionID int NULL,
LocationID int NULL,
Name nvarchar(60) NULL,
Crypt varchar(32) NULL,
Security int NULL,
Status int NULL,
PRIMARY KEY ( UserID ),
CONSTRAINT fk_OrgID_Users FOREIGN KEY (OrgID) REFERENCES Organisations(OrgID)
);
CREATE TABLE Organisations(
OrgID varchar(6) NOT NULL,
Name nvarchar(70) NOT NULL,
Address1 varchar(50) NULL,
Address2 varchar(50) NULL,
Address3 varchar(50) NULL,
Town varchar(20) NULL,
County varchar(20) NULL,
PostCode varchar(10) NULL,
NotificationEmail varchar(500) NOT NULL,
PRIMARY KEY ( OrgID )
)
But in MySQL Workbench, there are no relationships or foreign keys being created. If I look at the table data, and the foreign keys tab, theres nothing there?
I think I'm creating the foreign keys correctly, so is there a reason its not importing them?
On further research there were several things that I needed to do for this to work.
I had to make sure that the tables reverse engineered from MySQL were defined as InnoDB.
And I also had to remove the foreign key constraint from the create table command and create the foreign keys after the tables were created, like so:
CREATE TABLE Users (
UserID varchar(32) NOT NULL,
OrgID varchar(6) NOT NULL,
RegionID int NULL,
LocationID int NULL,
Name nvarchar(60) NULL,
Crypt varchar(32) NULL,
Security int NULL,
Status int NULL,
PRIMARY KEY ( UserID )
) ENGINE=InnoDB;
CREATE TABLE Organisations(
OrgID varchar(6) NOT NULL,
Name nvarchar(70) NOT NULL,
Address1 varchar(50) NULL,
Address2 varchar(50) NULL,
Address3 varchar(50) NULL,
Town varchar(20) NULL,
County varchar(20) NULL,
PostCode varchar(10) NULL,
NotificationEmail varchar(500) NOT NULL,
PRIMARY KEY ( OrgID )
) ENGINE=InnoDB;
ALTER TABLE Users ADD CONSTRAINT fk_OrgID_Users FOREIGN KEY (OrgID) REFERENCES Organisations(OrgID);
This then worked fine and the relationships were visible and connected in MySQL Workbench

#1005 - Can't create table 'workswell_database.skoleni' Novice user with MySQL

sorry for my stupid question,but I do database in MySQL and was so happy,when i finished.Unfortunately,I had found a lot of mistakes in my database n when i will properly fix a bug,so i've another. Also,this is my Database and that guy what really boring right now,please write about my bugs and solution for them.I novice as a programmer and this database i do about 4 days !
CREATE TABLE`Skoleni` (
`sk_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Cena` MEDIUMINT NOT NULL,
`Obsazenost` text NOT NULL,
`Kapacita` datetime NOT NULL,
`Popis` text,
`Prerekvizity` text,
`Certifikat` MEDIUMINT NOT NULL,
PRIMARY KEY (`sk_id`),
FOREIGN KEY (`sk_id`) REFERENCES Skoleni_has_Termin(`Skoleni_sk_id`),
FOREIGN KEY (`sk_id`) REFERENCES Skoleni_has_Uzivatel(`Skoleni_sk_id`)
);
CREATE TABLE `Skoleni_has_Termin`(
`Skoleni_sk_id`INT NOT NULL UNIQUE,
`Termin_ter_id` INT NOT NULL UNIQUE,
PRIMARY KEY (`Skoleni_sk_id`)
);
CREATE TABLE `Termin` (
`ter_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Datum_cas` DATETIME NOT NULL,
`Misto_mo_id` INT NOT NULL,
PRIMARY KEY (`ter_id`),
FOREIGN KEY (`ter_id`) REFERENCES Skoleni_has_Termin(`Termin_ter_id`)
);
CREATE TABLE `Misto` (
`mo_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`ulice` MEDIUMINT NOT NULL,
`cislo_popisne` MEDIUMINT NOT NULL,
`lat` FLOAT (10,6) NOT NULL,
`lng` FLOAT (10,6) NOT NULL,
PRIMARY KEY (`mo_id`)
)ENGINE = MYISAM;
SELECT TABLE.Misto(
INSERT (`ulice`, `cislo_popisne`, `lat`, `lng`),
VALUES (`dr_Zikmunda_Wintra_376_5``16000 Praha 6 Bubenec``14.407438``50.101049`)
);
CREATE TABLE `Skoleni_has_Uzivatel` (
`Skoleni_sk_id` INT NOT NULL UNIQUE,
`Uzivatel_uziv_id` INT NOT NULL UNIQUE,
PRIMARY KEY (`Skoleni_sk_id`)
);
CREATE TABLE `Uzivatel` (
`uziv_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Jmeno` VARCHAR(30) NOT NULL,
`Typ` MEDIUMINT UNIQUE,
`Heslo` VARCHAR(32) NOT NULL,
`Potvrzeni` VARCHAR(1) NOT NULL,
PRIMARY KEY (`uziv_id`),
FOREIGN KEY (`uziv_id`) REFERENCES Skoleni_has_Uzivatel(`Uzivatel_uziv_id`)
);
CREATE TABLE `Skoleni_has_Lektor` (
`Skoleni_sk_id` INT NOT NULL UNIQUE,
`Lektor_lek_id` INT NOT NULL UNIQUE,
PRIMARY KEY (`Lektor_lek_id`)
);
CREATE TABLE `Lektor` (
`lek_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`Titul'pred'` VARCHAR(10) NOT NULL,
`Jmeno` VARCHAR(20) NOT NULL,
`Prijmeni` VARCHAR(20) NOT NULL,
`Titul'za'` VARCHAR(10),
`Firma` VARCHAR(30),
`Rodne cislo` CHAR(11) NOT NULL,
`Datum narozeni` DATE NOT NULL,
PRIMARY KEY (`lek_id`)
);
CREATE TABLE `Firma` (
`fir_id` INT NOT NULL UNIQUE AUTO_INCREMENT,
`E-mail` VARCHAR(15) NOT NULL,
`Telefon` VARCHAR(15) NOT NULL,
`Web` VARCHAR(30),
`IC` CHAR(8) NOT NULL,
`DIC` VARCHAR(12) NOT NULL,
`Misto_mo_id` INT NOT NULL,
PRIMARY KEY (`fir_id`),
PRIMARY KEY (`Misto_mo_id`),
FOREIGN KEY (`Misto_mo_id`) REFERENCES Firma(`Misto_mo_id`)
);
The tables `skoleni_has_termin' and 'skoleni_has_lektor' are most likely not needed here. I would bring dates to trainings table and leave just lektor_id in skoleni table as relation between trainings and lecturers is 1:n not m:n (unless one training can have more than one lecturer)