Referenced table not found in the data dictionary mariadb - sql

so I have written this Mariadb code as the solution for an assignment and am running it on HeidiSQL. It should work in theory however I am getting the error message SQL Error (1005): Can't create table bestellung.arbeitetin (errno: 150 "Foreign key constraint is incorrectly formed"). Upon using show warning, the program elaborates that "referenced table bestellung.arbeitetin not found in the data dictionary". I am wondering, is there something wrong with the code?
Datum date not NULL,
Abholtermin DATE,
Kostenstelle int not NULL,
Abteilung char(5) not NULL,
Mitarbeiter int not NULL,
Telefon int not NULL,
primary key (Bestellnummer)
);
create table enthaelt (
FK_Bestellnummer int not NULL,
FK_Artikelnummer char(10) not NULL,
Menge int not NULL,
unique key (FK_Bestellnummer, FK_Artikelnummer)
);
alter table enthaelt ADD
constraint FK_ArtikelNr
foreign key (FK_Artikelnummer)
references Artikel (Artikelnummer);
alter table enthaelt ADD
constraint FK_BestellNr
foreign key (FK_Bestellnummer)
references Bestellung (Bestellnummer);
create table arbeitetin
(
FK_PersNr int not NULL,
FK_ProjektNr int not NULL,
unique key(FK_PersNr, FK_ProjektNr)
);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_MITARBEITER1
FOREIGN KEY (FK_PersNr)
REFERENCES Mitarbeiter (PersNr);
alter table arbeitetin ADD
constraint FK_ARBEITETIN_PROJEKT
foreign key (FK_ProjektNr)
references Projekt (ProjektNr);
alter table Mitarbeiter ADD
constraint FK_MITARBEITER_ABTEILUNG
foreign key (FK_Abkuerzung)
references Abteilung (Abkuerzung); ```

Related

Setting up indexes for multiple foreign keys

An error message regarding indexes displays when foreign keys are added using the following scripts. I have added primary keys and indexes different ways but not sure if the diagram is providing information about how to setup the indexes/primary keys that I'm not seeing.
CREATE TABLE aocommercial_building(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
owner VARCHAR(255) NULL,
owner2 VARCHAR(255) NULL,
);
CREATE TABLE aocommercial_heatcool(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
section INT NULL,
heat_cool_cd VARCHAR(255) NULL
);
CREATE TABLE aocommercial_unit(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
section INT NOT NULL,
occ_desc VARCHAR(255) NULL
);
CREATE TABLE aocom_misc_bldg(
parcel CHAR(25) NOT NULL,
suffix INT NOT NULL,
section INT NOT NULL,
misc_bldg_type VARCHAR(255) NULL
);
ALTER TABLE aocommercial_unit ADD FOREIGN KEY (parcel) REFERENCES aocommercial_building(parcel);
ALTER TABLE aocommercial_unit ADD FOREIGN KEY (suffix) REFERENCES aocommercial_building(suffix);
ALTER TABLE aocommercial_heatcool ADD FOREIGN KEY (parcel) REFERENCES aocommercial_unit(parcel);
ALTER TABLE aocommercial_heatcool ADD FOREIGN KEY (suffix) REFERENCES aocommercial_unit(suffix);
ALTER TABLE aocommercial_heatcool ADD FOREIGN KEY (section) REFERENCES aocommercial_unit(section);
ALTER TABLE aocom_misc_bldg ADD FOREIGN KEY (parcel) REFERENCES aocommercial_unit(parcel);
ALTER TABLE aocom_misc_bldg ADD FOREIGN KEY (suffix) REFERENCES aocommercial_unit(suffix);
ALTER TABLE aocom_misc_bldg ADD FOREIGN KEY (section) REFERENCES aocommercial_unit(section);
enter image description here
For each table, what column (or combination of columns) uniquely identifies each row? Then, include in each CREATE TABLE another line with PRIMARY KEY(...).
For each table, if there is no particular set of columns to uniquely define each row, then add
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id)
Look around; there are lots and lots of examples.

Add constraint to compare two attributes of different tables?

Here are my tables. I need to check that the 'program' attribute referenced in StudentsBranch with the table Students and the table Branches is the same. How can I do it?
CREATE TABLE Programmes (
name VARCHAR(200) UNIQUE NOT NULL,
CONSTRAINT pk_Programmes PRIMARY KEY (name)
);
CREATE TABLE Students (
id NUMERIC(10,0) UNIQUE NOT NULL,
program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Students PRIMARY KEY (idnr),
FOREIGN KEY (program) REFERENCES Programmes(name)
);
CREATE TABLE Branches (
name VARCHAR(200) UNIQUE NOT NULL,
program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Branches PRIMARY KEY (name, program),
FOREIGN KEY (program) REFERENCES Programmes(name)
);
CREATE TABLE StudentsBranch (
student NUMERIC(10,0) NOT NULL,
program VARCHAR(200) NOT NULL,
branch VARCHAR(200) NOT NULL,
CONSTRAINT pk_StudentsBranch PRIMARY KEY (student),
/* Below how the foreign keys I think should be */
FOREIGN KEY (student, program) REFERENCES Students(idnr, program),
FOREIGN KEY (branch, program) REFERENCES Branches(name, program)
/* I need to add a constraint to verify that the 'program' in Students
* and the 'program' in Branches are equivalent. How?
*/
);
You can't write that constraint with that existing database model you have now.
The only way I see you could do it, is by changing the primary key of Students to (id, program):
CREATE TABLE Students (
id NUMERIC(10,0) UNIQUE NOT NULL,
program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Students PRIMARY KEY (id, program),
FOREIGN KEY (program) REFERENCES Programmes(name)
);
Then the table StudentsBranch could naturally enforce both FKs with using the single column program, as in:
CREATE TABLE StudentsBranch (
student NUMERIC(10,0) NOT NULL,
program VARCHAR(200) NOT NULL,
branch VARCHAR(200) NOT NULL,
CONSTRAINT pk_StudentsBranch PRIMARY KEY (student),
FOREIGN KEY (student, program) REFERENCES Students (id, program),
FOREIGN KEY (branch, program) REFERENCES Branches (name, program)
);
It is always a good idea to have an numeric column of primary key and have primary key for every table.
Once you have primary key for every table you can referece primary key of a specific table and refere it as foerign key.
CREATE TABLE Programmes (
ID INT,
name VARCHAR(200) UNIQUE NOT NULL,
CONSTRAINT pk_Programmes PRIMARY KEY (ID)
);
CREATE TABLE Students(
id INT,
ProgrammID INT NOT NULL,
CONSTRAINT pk_Students PRIMARY KEY (ID),
FOREIGN KEY (ProgrammID) REFERENCES Programmes(ID)
);
CREATE TABLE Branches (
BranchID INT,
ProgrammID INT NOT NULL,
name VARCHAR(200) UNIQUE NOT NULL,
--program VARCHAR(200) NOT NULL,
CONSTRAINT pk_Branches PRIMARY KEY (BranchID, ProgrammID),
FOREIGN KEY (ProgrammID) REFERENCES Programmes(ID)
);
CREATE TABLE StudentsBranch (
StudentsBranchID INT,
studentID INT NOT NULL,
ProgrammID INT NOT NULL,
BranchID INT NOT NULL,
CONSTRAINT pk_StudentsBranch PRIMARY KEY (StudentsBranchID),
FOREIGN KEY (ProgrammID) REFERENCES Programmes(id),
FOREIGN KEY (studentID) REFERENCES Students(id),
FOREIGN KEY (BranchID, ProgrammID) REFERENCES Branches(BranchID, ProgrammID)
);

Foreign key in SQL Server - which style to use?

In my database, I have the following code
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
FOREIGN KEY(userID) REFERENCES Users (userID)
);
However, here on stackOverflow and multiple other sites, people suggest writing it like this:
CREATE TABLE [Users]
(
userID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Username VARCHAR(255),
Password VARCHAR(255)
);
CREATE TABLE [Image]
(
ImageID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
Imagename VARCHAR,
userID INT,
CONSTRAINT fk_Users
FOREIGN KEY(userID) REFERENCES Users (userID)
);
I've tried executing both statements, and it seems to do the same..
What am I missing, what's the trick when writing CONSTRAINT fk_Users?
Writing constraint allows you to name the constraint.
In general, you notice this when the constraint is violated. If you have an opportunity to name the constraint, the error message will make more sense.
For instance, this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"fk_image_userId". The conflict occurred in database "rextester",
table "dbo.Users", column 'userID'.
The statement has been terminated.
is clearer than this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK__Image__userID__09211CD4". The conflict occurred in database
"rextester", table "dbo.Users", column 'userID'.
The statement has been terminated.
In addition, the constraint name is used in the alter table when you drop or disable the constraint, so having a reasonably named constraint makes that easier.

I have no idea why I get an error when putting the foreing keys in MariaDB

I have no idea why I get an error when putting the foreing keys in MariaDB
I drop the full database if it exists
drop database if exists proveedoresCarrito;
create database proveedoresCarrito;
use proveedoresCarrito;
And now I'm going to create the tables
CREATE TABLE INVENTARIO (
NUMPIEZA CHAR(16) NOT NULL,
NUMBIN SMALLINT NOT NULL,
CANTDISPONIBLE SMALLINT,
FECHARECUENTO DATE,
PERIODORECUEN SMALLINT,
CANTAJUSTE SMALLINT,
CARTREORD SMALLINT,
PUNTOREORD SMALLINT);
CREATE TABLE LINPED (
NUMPEDIDO SMALLINT NOT NULL,
NUMLINEA SMALLINT NOT NULL,
NUMPIEZA CHAR(16),
PRECIOCOMPRA INTEGER,
CANTPEDIDA SMALLINT,
FECHARECEP DATE,
CANTRECIBIDA SMALLINT);
CREATE TABLE PEDIDO (
NUMPEDIDO SMALLINT NOT NULL,
NUMVEND SMALLINT,
FECHA DATE);
CREATE TABLE PIEZA (
NUMPIEZA CHAR(16) NOT NULL,
NOMPIEZA CHAR(30),
PRECIOVENT INTEGER);
CREATE TABLE PRECIOSUM (
NUMPIEZA CHAR(16) NOT NULL,
NUMVEND SMALLINT NOT NULL,
PRECIOUNIT INTEGER,
DIASSUM SMALLINT,
DESCUENTO SMALLINT);
CREATE TABLE VENDEDOR (
NUMVEND SMALLINT NOT NULL,
NOMVEND CHAR(30),
NOMBRECOMER CHAR(30),
TELEFONO CHAR(15),
CALLE CHAR(30),
CIUDAD CHAR(20),
PROVINCIA CHAR(20),
COD_POSTAL CHAR(5));
create table usuarios(
nombre SMALLINT NOT NULL,
pass CHAR(15)
);
I Set up the primary keys
ALTER TABLE INVENTARIO ADD CONSTRAINT CP_INVENTARIO PRIMARY KEY (NUMBIN);
ALTER TABLE LINPED ADD CONSTRAINT CP_LINPED PRIMARY KEY (NUMPEDIDO, NUMLINEA);
ALTER TABLE PEDIDO ADD CONSTRAINT CP_PEDIDO PRIMARY KEY (NUMPEDIDO);
ALTER TABLE PIEZA ADD CONSTRAINT CP_PIEZA PRIMARY KEY (NUMPIEZA);
ALTER TABLE PRECIOSUM ADD CONSTRAINT CP_PRECIOSUM PRIMARY KEY (NUMPIEZA, NUMVEND);
ALTER TABLE VENDEDOR ADD CONSTRAINT CP_VENDEDOR PRIMARY KEY (NUMVEND);
AND FINALLY i set up the foreign keys
ALTER TABLE INVENTARIO ADD CONSTRAINT CP_INVENTARIO PRIMARY KEY (NUMBIN);
ALTER TABLE LINPED ADD CONSTRAINT CP_LINPED PRIMARY KEY (NUMPEDIDO, NUMLINEA);
ALTER TABLE PEDIDO ADD CONSTRAINT CP_PEDIDO PRIMARY KEY (NUMPEDIDO);
ALTER TABLE PIEZA ADD CONSTRAINT CP_PIEZA PRIMARY KEY (NUMPIEZA);
ALTER TABLE PRECIOSUM ADD CONSTRAINT CP_PRECIOSUM PRIMARY KEY (NUMPIEZA, NUMVEND);
ALTER TABLE VENDEDOR ADD CONSTRAINT CP_VENDEDOR PRIMARY KEY (NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_NOMBRE FOREIGN KEY (nombre) REFERENCES VENDEDOR(NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_PASS FOREIGN KEY (pass) REFERENCES VENDEDOR(TELEFONO);
However, all the foreign keys work correctly except for the last two
when i run the sql script i get this error:
Error de SQL (1822): Failed to add the foreign key constaint. Missing index for constraint 'CA_VENDEDOR_USUARIOS_PASS' in the referenced table 'vendedor'
if I drop the last two foreign keys the error disappears
Anyone can give me a solution?
Look closely at your "set up the foreign keys" code. It creates primary keys again (except the two last lines).
Table usuarios seems to have no primary key.
ALTER TABLE usuarios ADD CONSTRAINT CP_usuarios PRIMARY KEY (nombre);
Delete the first 6 lines and keep only these
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_NOMBRE
FOREIGN KEY (nombre)
REFERENCES VENDEDOR(NUMVEND);
ALTER TABLE usuarios ADD CONSTRAINT CA_VENDEDOR_USUARIOS_PASS
FOREIGN KEY (pass)
REFERENCES VENDEDOR(TELEFONO);
Also (and this is what generates your error), you are trying to add a foreign key to a column VENDEDOR(TELEFONO) which is not a primary key nor has a UNIQUE constraint.
According to Microsoft:
A foreign key constraint does not have to be linked only to a primary key constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
See: Create Foreign Key Relationships
Add this before creating the foreign keys:
ALTER TABLE VENDEDOR ADD CONSTRAINT UX_telefono UNIQUE (TELEFONO);
A foreign key has to reference always a primary key.
For you to reference the table VENDEDOR you should use the columns that compose its PK. In this example, NUMVEND.
If you need any suggestions on what to do, i'd have to know what are your intentions on this DB structure.

CONSTRAINT to foreign keys to one table - causes error

I am starting to build something like system up to the just cooperate with suggestions coming into the database called ForslagOpslag.
Every time I try to update table with likes, you will see it with this one error:
Update cannot proceed due to validation errors. Please correct the following errors and try again.
SQL71516 :: The referenced table '[dbo].[ForslagOpslag]' contains no
primary or candidate keys that match the referencing column list in
the foreign key. If the referenced column is a computed column, it
should be persisted.
Here is how I built my ForslagOpslagLikes table:
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
);
Reason I have both fk_brugerid and getid is for sure me that the user can not vote / like more once!
The way I have built my ForslagOpslag table:
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
like this to be my like system do:
ForslagOpslagLikes -> fk_brugerid to ForslagOpslag -> fk_brugerid
ForslagOpslagLikes -> getid to ForslagOpslag -> id
Well - the error seems pretty clear: you're trying to estabslish a foreign key relationship to ForslagOpslag.fk_brugerid here:
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslag]([fk_brugerid])
but that column is NOT the primary key of that other table - and it's not a UNIQUE constraint either - so you cannot reference that column in a foreign key relationship.
But the column(s) that a foreign key references must be the primary key of that other table - or in SQL Server, it's good enough if there's a UNIQUE constraint on that column. You must ensure that the values you reference in FroslagOpslag only match a single column in that table - otherwise, you cannot establish a foreign key relationship
Try to remove the foreing key in your first table like this
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_ToGetid]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id]),
);
Then you need to add the foreign key in the second table with the primary key with the first table
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR (MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_ForslagOpslagLikes_ToForslagBrugerid]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[ForslagOpslagLikes]([fk_brugerid])
);
You sound scandinavian, and Bruger means User (for all the non-scandinavians here).
What you appear to want is a Bruger (User) table, where fk_brugerid in ForslagOpslag is the user who created the record with opretdato being the creation date, and ForslagOpslagLikes is an association table of users who likes the ForslagOpslag with opretdato being the date they clicked on "Like".
CREATE TABLE [dbo].[Bruger]
(
[brugerid] INT IDENTITY (1, 1) NOT NULL,
...,
CONSTRAINT [PK_Bruger]
PRIMARY KEY CLUSTERED ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslag]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[text] NVARCHAR(MAX) NOT NULL,
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
CONSTRAINT [PK_ForslagOpslag]
PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [FK_ForslagOpslag_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid])
);
CREATE TABLE [dbo].[ForslagOpslagLikes]
(
[fk_brugerid] INT NOT NULL,
[opretdato] DATETIME NOT NULL,
[getid] INT NOT NULL,
CONSTRAINT [PK_ForslagOpslagLikes]
PRIMARY KEY CLUSTERED ([fk_brugerid], [getid]),
CONSTRAINT [FK_ForslagOpslagLikes_Bruger]
FOREIGN KEY ([fk_brugerid])
REFERENCES [dbo].[Bruger] ([brugerid]),
CONSTRAINT [FK_ForslagOpslagLikes_ForslagOpslag]
FOREIGN KEY ([getid])
REFERENCES [dbo].[ForslagOpslag]([Id])
);