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

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.

Related

Referenced table not found in the data dictionary mariadb

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); ```

Foreign key 'fk_orders_SalesRep' references invalid column 'snum' in referencing table 'orders'

What am I doing wrong? I'm trying to add a foreign key to an existing table
ALTER TABLE orders
ADD CONSTRAINT fk_orders_SalesRep
FOREIGN KEY (snum)
REFERENCES SalesRep(snum);
Table information
create table SalesRep(
snum varchar(5) primary key,
sname varchar(10),
hours Int
)
create table orders(
odId varchar(5) primary key,
itId varchar(5) foreign key(itId) references items(itId)
)
Like Martin said add the column first
ALTER TABLE orders
ADD snum varchar(5);
And then add the fk
ALTER TABLE orders
ADD CONSTRAINT fk_orders_SalesRep
FOREIGN KEY (snum)
REFERENCES SalesRep(snum);

CREATED OR MODIFY A TABLE WHICH HAVE A COMBINED PRIMARY KEY, FORM FROM 3 OF THEIR ATTRIBUTES

I'm trying to created a table, and give as a primary key, the 3 attributes, which it have.
The code is below:
CREATE TABLE compra
(
dni_cli VARCHAR2(50),
cod_prod NUMBER(10) NOT NULL,
cantidad NUMBER (10),
CONSTRAINT pk_compra PRIMARY KEY (dni_cli, cod_prod, cantidad);
CONSTRAINT pelicula_codigo_prod_fg FOREIGN KEY (cod_prod) REFERENCES producto(cod_prod),
CONSTRAINT pelicula_codigo_cli_fg FOREIGN KEY (dni_cli) REFERENCES cliente(dni)
);
I also tried to create the table first, and then, add the constraint in order to create the combined PRIMARY KEY with the alter table, but is doesn't work.
The code is this:
ALTER TABLE CONSTRAINT pk_compra PRIMARY KEY (dni_cli, cod_prod, cantidad);
If the primary key already exists you need to drop the key:
ALTER TABLE compra drop constraint pk_compra;
then add the key:
ALTER TABLE compra add constraint pk_compra primary key (city_id, buildtime, time);
If the primary key does not exist in the table then just use the second command line.
Also as #stickybit noted your table has an error. This is the code without an error:
CREATE TABLE compra (
dni_cli VARCHAR2(50),
cod_prod NUMBER(10) NOT NULL,
cantidad NUMBER (10),
CONSTRAINT pk_compra PRIMARY KEY (dni_cli,cod_prod,cantidad), --<<change here
CONSTRAINT pelicula_codigo_prod_fg FOREIGN KEY (cod_prod) REFERENCES producto(cod_prod),
CONSTRAINT pelicula_codigo_cli_fg FOREIGN KEY (dni_cli) REFERENCES cliente(dni));

ERROR: No unique constraint matching when having FK

I have three tables that are linked together
My script:
-- Ticket --
CREATE TABLE public.ticket (
id bigint NOT NULL,
libelle character varying(255) NOT NULL,
description character varying(255) NOT NULL,
status character varying(255) NOT NULL,
date_creation timestamp NOT NULL,
date_modification timestamp NOT NULL,
user_createur_id bigint,
referent_realisateur_id bigint,
CONSTRAINT pk_ticket PRIMARY KEY (id)
);
-- Ticket_Avance TABLE --
CREATE TABLE public.ticket_avance (
id bigint NOT NULL,
date_livraison_souhaite timestamp NOT NULL,
date_engagement_livraison timestamp NOT NULL,
referent_demandeur_id bigint
);
ALTER TABLE public.ticket_avance ADD CONSTRAINT "fk_ticket_ticketAvance" FOREIGN KEY (id)
REFERENCES public.ticket (id) MATCH SIMPLE
ON DELETE NO ACTION ON UPDATE NO ACTION;
-- Demande_Travaux TABLE --
DROP TABLE IF EXISTS public.demande_travaux CASCADE;
CREATE TABLE public.demande_travaux (
id bigint NOT NULL,
contrat_id bigint
);
ALTER TABLE public.demande_travaux ADD CONSTRAINT "fk_ticketAvance_DDT" FOREIGN KEY (id)
REFERENCES public.ticket_avance (id) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
I have this error on the demand_travaux creation
SQL Error [42830]: ERROR: there is no unique constraint matching given keys for referenced table "ticket_avance"
ERROR: there is no unique constraint matching given keys for referenced table "ticket_avance"
ERROR: there is no unique constraint matching given keys for referenced table "ticket_avance"
You have forgotten to declare column ID in table ticket_avance as primary key.
Please use the following SQL:
-- Ticket_Avance TABLE --
CREATE TABLE public.ticket_avance (
id bigint NOT NULL,
date_livraison_souhaite timestamp NOT NULL,
date_engagement_livraison timestamp NOT NULL,
referent_demandeur_id bigint,
CONSTRAINT pk_avance PRIMARY KEY (id) --- add this
);
you need add constraint in Ticket_Avance table because you provide reference this id to demande_travaux
-- Ticket_Avance TABLE --
CREATE TABLE ticket_avance (
id bigint NOT NULL,
date_livraison_souhaite timestamp NOT NULL,
date_engagement_livraison timestamp NOT NULL,
referent_demandeur_id bigint,
CONSTRAINT pk_ticket_avance PRIMARY KEY (id) //constraint that you need
);
ALTER TABLE demande_travaux ADD CONSTRAINT "fk_ticketAvance_DDT" FOREIGN KEY (id)
REFERENCES ticket_avance (id) MATCH FULL
ON DELETE NO ACTION ON UPDATE NO ACTION;
here is the demo link of your full query
A foreign key constraint has to target a primary key or unique constraint. The database has to be able to identify a single row in the "parent" table.
You could add primary key constraints:
ALTER TABLE public.ticket_avance ADD PRIMARY KEY (id);
In addition, you should have an index on the column on which the foreign key is defined, particularly if you plan to delete parent rows. With the primary key above, you have such an index on id, but you also should have one on demande_travaux.
The simplest way is to define id as primary key there too:
ALTER TABLE public.demande_travaux ADD PRIMARY KEY (id);

How to make Primary Key in Sql Server Using Alter Statement?

I have forgot create a primary key for my table. Now I want to update the DocDay_Id column and make it the primary key. How can I do it?
My code is below.
I tried this syntax but it is not correct.
ALTER TABLE DoctorDays
ALTER COLUMN DocDay_Id int IDENTITY(1,1) PRIMARY KEY NOT NULL
Create table DoctorDays
(
DocDay_Id int IDENTITY(1,1) NOT NULL,
Doc_Id int FOREIGN KEY REFERENCES Doctor(Doc_Id) NOT NULL,
Day_Id int FOREIGN KEY REFERENCES Dayss(Day_Id) NOT NULL
)
To create a clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY CLUSTERED (DocDay_Id);
To create a non clustered primary key on an existing table:
ALTER TABLE DoctorDays ADD CONSTRAINT PK_DocDays
PRIMARY KEY NONCLUSTERED (DocDay_Id);
FIDDLE DEMO HERE
See the document in below link:
Alter Statement Documents