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

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

Related

How can I fix this error? there is no unique constraint matching given keys for referenced table "products"

CREATE TABLE order_items
(
order_id int,
product_id int,
quantity int,
CONSTRAINT order_items_pk
PRIMARY KEY(order_id,product_id),
CONSTRAINT order_items_order_id_fk
FOREIGN KEY(order_id) REFERENCES orders(id),
CONSTRAINT order_items_product_id_fk
FOREIGN KEY(product_id) REFERENCES products(id)
);
To create this table, you will first have to create the tables mentioned in the foreign key declarations. Those tables are orders and products.
If you don't create those tables first, the table server cannot handle those constraints.

Problems when creating a table referencing other with FK

I'm trying to create a database for a project that works like a school with some teachers,courses,classes etc.
I need to create a new Table involving 2 tables however I'm getting an error when creating the table Classes_Teachers.
There are no primary or candidate keys in the referenced table 'Classes' that match the referencing column list in the foreign key 'FK__Classes_T__Class__11007AA7'.
Here is my SQL Code:
CREATE TABLE Teachers(
id INT,
name varchar(40),
email varchar(30) FOREIGN KEY REFERENCES Users(email),
PRIMARY KEY(id)
);
CREATE TABLE Courses(
name varchar(20),
acr varchar(4),
teacher int FOREIGN KEY REFERENCES Teachers(id),
PRIMARY KEY(acr)
);
CREATE TABLE Classes(
id varchar(2),
courses_acronym varchar(4) FOREIGN KEY REFERENCES Courses(acr),
year_Semesters varchar(5),
PRIMARY KEY(id,courses_acronym),
);
CREATE TABLE Classes_Teacher(
Classes_id varchar(2) FOREIGN KEY REFERENCES Classes(id),
Teachers_id INT FOREIGN KEY REFERENCES Teachers(id),
courses_acronym varchar(4) FOREIGN KEY REFERENCES Classes(courses_acronym),
PRIMARY KEY(Classes_id,courses_acronym)
);
The error comes from the foreign keys declared in table Classes_Teacher. To relate to the Classes table, you want to use both primary columns of the referred tables, instead of twn separated foreign keys.
Consider:
CREATE TABLE Classes_Teacher(
Classes_id varchar(2),
Teachers_id INT FOREIGN KEY REFERENCES Teachers(id),
courses_acronym varchar(4),
FOREIGN KEY (Classes_id, courses_acronym) REFERENCES Classes(id, courses_acronym),
PRIMARY KEY(Classes_id,courses_acronym)
);
Demo on DB Fiddle.
In table Classes you define a Primary Key on two columns. This is probably not needed if courses_acronym depends on ID.
CREATE TABLE Classes(
id varchar(2),
courses_acronym varchar(4) FOREIGN KEY REFERENCES Courses(acr),
year_Semesters varchar(5),
PRIMARY KEY(id),
);
In table Classes_Teacher you refer Classes twice. Shouldn't the second Foreign Key refer Courses?
CREATE TABLE Classes_Teacher(
Classes_id varchar(2) FOREIGN KEY REFERENCES Classes(id),
Teachers_id INT FOREIGN KEY REFERENCES Teachers(id),
courses_acronym varchar(4) FOREIGN KEY REFERENCES Courses(acr),
PRIMARY KEY(Classes_id,courses_acronym)
);

Alter Foreign Key Constraint Primary Key Error

I'm trying to drop and recreate a foreign key constraint, but I get an error
There are no primary or candidate keys in the referenced table 'inventory' that match the referencing column list in the foreign key 'fkInventory_VendorsInventory'.
I have already gone into the table design for both tables referenced in the code, and ensured that the column being referenced is a primary key.
ALTER TABLE inventory_vendors
DROP CONSTRAINT fkInventory_VendorsInventory;
ALTER TABLE inventory_vendors
ADD CONSTRAINT fkInventory_VendorsInventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
I have done such a drop and recreation before with no problems at all with another set of tables (unfortunately i don't remember which tables they were).
As you mentioned in comments, you have 2 primary key columns in the Inventory table:
one is itemnum, the other is store_id
I prepare a sample SQL here: 2 tables created
CREATE TABLE inventory
(
itemnum INT,
store_id INT,
inventoryDesc char(200),
primary key (itemnum, store_id)
);
CREATE TABLE inventory_vendors
(
inventory_vendors int,
itemnum INT,
store_id INT,
VendorDetails varchar(200),
primary key (inventory_vendors)
);
Create Unique constraint for one of the primary key. Here I am creating UNIQUE constraint for itemnum column
ALTER TABLE inventory
ADD CONSTRAINT [IX_inventory] UNIQUE ( [itemnum] )
GO
Then execute your script for creating the foreign key constraint on inventory_vendors for itemnum column and you can drop them as well.
ALTER TABLE inventory_vendors
ADD CONSTRAINT fk_Inventory_Vendors_Inventory
FOREIGN KEY(itemnum) REFERENCES inventory(itemnum)
ON UPDATE CASCADE
ON DELETE CASCADE
ALTER TABLE inventory_vendors
DROP CONSTRAINT fk_Inventory_Vendors_Inventory;
Hope this might help you..

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.

two columns referencing a single column in another table

A similar question is asked here multiple foreign keys referencing single column in other table
but the syntax is not shown in the answer. I would like to know how this can be accomplished in SQL server. The following syntax gives error
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemIssue_Person
FOREIGN KEY (PersonID, AdvisorID) REFERENCES Person (PersonID)
;
ERROR: Number of referencing columns in foreign key differs from number of referenced columns, table 'ItemIssue'.
-- Create Tables
CREATE TABLE ItemIssue (
ItemIssueID int identity(1,1) NOT NULL,
PersonID int,
AdvisorID int,
)
;
CREATE TABLE Person (
PersonID int NOT NULL,
Name nvarchar(500),
)
;
You need to define two foreign keys, one for each column:
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemIssue_Person
FOREIGN KEY (PersonID) REFERENCES Person (PersonID)
;
ALTER TABLE ItemIssue ADD CONSTRAINT FK_ItemAdvisor_Person
FOREIGN KEY (AdvisorID) REFERENCES Person (PersonID)
;
It is impossible to create one foreign key for two columns referencing one column. Create them seperate:
ALTER TABLE ItemIssue
ADD CONSTRAINT FK_ItemIssue_Person_Person FOREIGN KEY (PersonID) REFERENCES Person (PersonID),
ADD CONSTRAINT FK_ItemIssue_Advisor_Person FOREIGN KEY (AdvisorID) REFERENCES Person (PersonID);
To define two foreign keys, one for each column-
Table
Contract - HospidPharmacyId Column
Hospice- HospiceID PK
Pharmacy PharmacyId Pk
Using Following Query we can apply 2 Foreign Key for 1 column.
Alter Table Contract
Add Constraint fk_pharmacyID Foreign Key ([HospIDPharmID]) references Pharmacy([PharmacyID])
Alter TAble contract
Add Constraint Fk_hospId Foreign key ([HospIDPharmID]) references Hospice(HospiceID)
In the Contract Table for column-HospidPharmacyId we can insert common value in both the
tables. those which are present in hospice & not in Pharmacy then we cant insert that value in
contract table & vice versa.