sql error with foreign key - sql

I have the error here:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CHITIETDH__MaDH__4316F928". The conflict occurred in database [...]
But with the code here :
create database abc_1quanly111
use abc_1quanly111
create table abc_1nhacc
(
MaNhaCC varchar(10) primary key,
TenNhaCC varchar(50),
DiaChiCC varchar(50),
Telephone varchar(50),
)
create table abc_1mamathang
(
MaMH varchar(10) primary key,
TenMH varchar(50) not null,
DonGia int check (DonGia>0),
SoLuong int ,
MaNhaCC varchar(10) foreign key references abc_1nhacc(MaNhaCC)
)
--Insert Nha CC --- Values -----
INSERT INTO abc_1nhacc VALUES('NC1','Phong Vu','123 NTMK ','0283232677')
INSERT INTO abc_1nhacc VALUES('NC2','Phong Hoang','123 NTD ','0290120217'),('NC3','THE GIOI DI DONG','12 LE VAN VIET ','028382901'),('NC4','NGUYEN KIM','23 LE DUAN ','01283232677'),('NC5','Phong KIM','13 LE LOI ','0288292677')
select * from abc_1nhacc
--Insert Mat Hang ---- Values ----
insert into abc_1mamathang values('M1','Laptop Sony',1000000,100,'NC1')
,
('M2','Laptop MSI GAMING',3200000,1,'NC2'),
('M3','Laptop ASUS',900000,10,'NC3'),
('M4','Laptop ACER',1340000,20,'NC4'),
('M5','Xperia A',10000,10,'NC5')
select * from abc_1nhacc
select * from abc_1mamathang
create table abc_1khachhang
(
MaKhachHang varchar(10) primary key,
TenKhachHang varchar(50),
DiaChiKhachHang varchar(50),
PhoneKhachHang varchar(10),
)
--Insert Khach Hang ---- Values ----
INSERT INTO abc_1khachhang values('KH1','Anh A','121 Le Duan Q1','09878721'),('KH2','Anh B','12 Quang Trung Q12','01878221'),('KH3','Anh C','331 Nguyen Thi Minh Khai','028787221'),('KH4','Anh D','23 Le Quang Dinh','09872321'),('KH5','Bac AD','','098787211')
create table abc_1dondathang
(
MaSoDonDatHang varchar(10) primary key,
NgayDatHang DATE Default GetDate(),
MaKhachHang varchar(10) foreign key references abc_1khachhang(MaKhachHang)
)
CREATE TABLE CHITIETDH
(
MaDH varchar(10) foreign key references abc_1dondathang,
MaMH varchar(10) foreign key references abc_1mamathang,
Soluong int check (soluong>0)
constraint pk_DHMH primary key(MaDH ,MaMH)
)
select * from abc_1dondathang
select * from abc_1mamathang
select * from CHITIETDH
insert into CHITIETDH values('DH1','MH1',12) // errors
select * from CHITIETDH
I don't know solution how to fix that, can anyone help me thanks.

Your table CHITIETDH has a foreign key in table abc_1dondathang.
You try to insert values to CHITIETDH while abc_1dondathang is empty. You must all the values under this column MaDH varchar(10) foreign key references abc_1dondathang will exist in abc_1dondathang before you insert something in CHITIETDH.
You can read here more.

Related

How to execute an entire table and create a database diagram

When I run my query, only one of my rows is displayed.
I also need to create a database diagram from these 3 tables
Can someone please assist me on how to do that?
CREATE DATABASE Lab301;
CREATE TABLE Supplier(
SupplierID NVARCHAR(50),
Name NVARCHAR(50),
Address NVARCHAR(50),
PRIMARY KEY (SupplierID)
)
INSERT INTO Supplier(SupplierID,Name,Address)
VALUES('S01','ABC Company','Penang');
INSERT INTO Supplier(SupplierID,Name,Address)
VALUES('S02','XYZ Company','Johor');
INSERT INTO Supplier(SupplierID,Name,Address)
VALUES('S03','HJK Company','Selagnor');
INSERT INTO Supplier(SupplierID,Name,Address)
VALUES('S04','PQR Company','Selagnor');
SELECT * FROM Supplier;
CREATE TABLE Product(
ProductID NVARCHAR(50),
Name NVARCHAR(50),
PriceRM DECIMAL(10,2),
QuantitInStock INTEGER,
PRIMARY KEY (ProductID),
)
INSERT INTO Product(ProductID,Name,PriceRM,QuantitInStock)
VALUES('P01','Keyboard','103.55','60');
INSERT INTO Product(ProductID,Name,PriceRM,QuantitInStock)
VALUES('P02','Mouse','30.90','70');
INSERT INTO Product(ProductID,Name,PriceRM,QuantitInStock)
VALUES('P03','Monitor','200','80');
INSERT INTO Product(ProductID,Name,PriceRM,QuantitInStock)
VALUES('P04','Pendrive','40.30','50');
SELECT * FROM Product;
CREATE TABLE Supplies(
SuppliesID NVARCHAR(50),
SupplierID NVARCHAR(50),
ProductID NVARCHAR(50),
SuppliedDate DATE,
QuantitySupplied INTEGER,
PRIMARY KEY(SuppliesID),
FOREIGN KEY(SupplierID) REFERENCES Supplier(SupplierID),
FOREIGN KEY(ProductID) REFERENCES Product(ProductID),
)
INSERT INTO Supplies(SuppliesID,SupplierID,ProductID,SuppliedDate,QuantitySupplied)
VALUES('001','S01','P01','11/1/17','100');
INSERT INTO Supplies(SuppliesID,SupplierID,ProductID,SuppliedDate,QuantitySupplied)
VALUES('002','S01','P02','22/2/2017','200');
INSERT INTO Supplies(SuppliesID,SupplierID,ProductID,SuppliedDate,QuantitySupplied)
VALUES('003','S01','P03','NULL','300');
INSERT INTO Supplies(SuppliesID,SupplierID,ProductID,SuppliedDate,QuantitySupplied)
VALUES('004','S02','P03','30/4/2017','400');
SELECT * FROM Supplies;

ALTER TABLE statement conflicted with the FOREIGN KEY constraint

When creating the foreign key I came across this error. Below is my code.
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int
)
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
alter table tblPerson add constraint tblPerson_GenderId_FK
foreign key (GenderId) references tblGender(ID)
You want to identify any "do not align" rows....
I have made the below.
You won't be able to add the FK constraint, if any rows come back from the SELECT query.
I have also removed the hungarian notation for "tbl". I would advise against it.
create table dbo.Person(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int )
create table dbo.Gender (
ID int not null primary key,
Gender varchar(50) not null
)
/* any rows below? your FK creation will fail */
Select *, p.GenderId as 'HoustonWeHaveAProblemValue' from dbo.Person p Where Not Exists (Select 1 from dbo.Gender g where g.ID = p.GenderId)
alter table dbo.Person add constraint Person_GenderId_FK
foreign key (GenderId) references dbo.Gender(ID)
Hi please use the following code to achieve your goal :
1-First create tblGender:
create table tblGender (
ID int not null primary key,
Gender varchar(50) not null
)
2-Then create table tblPerson with the relationship between 2 tables since the beginning:
create table tblPerson(
ID int not null primary key,
Fullname varchar(50) not null,
Email varchar(50) not null,
GenderId int references tblGender(ID)
)
works fine.

update a select query in oracle DB

I have 5 tables in a DB like this (script below)::
DB SCRIPT
CREATE TABLE EQUIPE (
code_equipe char(3) primary key,
nom varchar(30),
directeur varchar(30));
CREATE TABLE PAYS (
code_pays varchar(3) primary key,
nom varchar(20));
CREATE TABLE COUREUR (
num_dossart number(3) primary key,
code_equipe char(3),
nom varchar(30),
code_pays varchar(3));
CREATE TABLE ETAPE (
num_etape number(1) primary key,
date_etape date,
kms number(3),
ville_depart varchar(20),
ville_arrivee varchar(20));
CREATE TABLE TEMPS (
num_dossart number(3),
num_etape number(1),
temps_realise number(6),
primary key(num_dossart,num_etape));
ALTER table COUREUR add CONSTRAINT FK_avoir_code_equipe FOREIGN KEY (code_equipe) REFERENCES EQUIPE(code_equipe);
ALTER table COUREUR add CONSTRAINT FK_avoir_code_pays FOREIGN KEY (code_pays) REFERENCES PAYS(code_pays);
ALTER table TEMPS add CONSTRAINT FK_avoir_num_dossart FOREIGN KEY (num_dossart) REFERENCES COUREUR(num_dossart);
ALTER table TEMPS add CONSTRAINT FK_avoir_num_etape FOREIGN KEY (num_etape) REFERENCES ETAPE(num_etape);
and my query
select num_etape,max(temps_realise) from TEMPS group by num_etape
gave this result
and i want to update it to give result like this
this is
If I read it correctly, a simple join does the job:
select t.num_etape,
c.nom,
max(n.temps_realise)
from temps t join coureur c on c.num_dossart = t.num.dossart
group by t.num_etape,
c.nom;
I have solved my question thanks guys
select num_dossart,nom,num_etape,dernier from COUREUR C,
(select num_etape ,max(temps_realise) as dernier from TEMPS GROUP BY num_etape) T
where num_dossart =
(select num_dossart from TEMPS where temps_realise = dernier )

ERROR: there is no unique constraint matching given keys for referenced table

I am getting an error when i create my tabels.
The problem is that AssCode is not unique, so i can set it to unique, the combination of courseCode and AssCode is unique, thats why they are set as primary keys. I am using postgressql
here is the error:
ERROR: there is no unique constraint matching given keys for referenced table "assignments"
SQL state: 42830
here is my code:
CREATE TABLE Teachers (
BSN int primary key,
Surname varchar(40) NOT NULL,
Name varchar(40) NOT NULL
);
CREATE TABLE Courses (
CourseCode varchar(10) primary key,
Name varchar(20) NOT NULL
);
CREATE TABLE Assignments (
CourseCode varchar(10) REFERENCES Courses ON DELETE CASCADE,
AssCode varchar(10),
primary key(CourseCode,AssCode),
DependOn varchar(10),
Year date,
week int
);
CREATE TABLE WorkOn (
BSN int REFERENCES Teachers(BSN),
CourseCode varchar(10) REFERENCES Assignments(CourseCode),
AssCode varchar(10) REFERENCES Assignments(AssCode),
primary key (CourseCode,BSN,AssCode)
);
I found the answer:
CREATE TABLE WorkOn (
BSN int primary key REFERENCES Teachers(BSN),
CourseCode varchar(10),
AssCode varchar(10),
foreign key (CourseCode, AssCode) references Assignments (CourseCode, AssCode)
);

Msg 2627, occured while using IDENT_CURRENT()

DDL:
CREATE TABLE OSOBA
(
id INT PRIMARY KEY not null IDENTITY,
imie VARCHAR(30) not null,
nazwisko VARCHAR(40) not null,
zawod VARCHAR(30) not null,
dataUrodzenia DATE,
plec BIT not null,
narodowosc VARCHAR(30) not null,
);
CREATE TABLE OSOBISTOSCI
(
nazwaMiasta VARCHAR(30) not null,
id INT not null,
adres VARCHAR(50),
czy BIT,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES OSOBA,
FOREIGN KEY (nazwaMiasta) REFERENCES MIASTA,
);
CREATE TABLE ARCHITEKCI
(
id INT not null,
uprawnienia VARCHAR(30) UNIQUE,
styl VARCHAR(30) not null,
liczba INT not null,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES OSOBA,
);
And I have these insert statements:
-- these work fine
INSERT INTO OSOBA (imie,nazwisko,zawod,dataUrodzenia,plec,narodowosc) VALUES ('Lech', 'Wałęsa', 'Elektryk', '19430129', 1, 'Polak');
INSERT INTO OSOBISTOSCI (nazwaMiasta, id, adres, czy) VALUES ('Gdańsk', IDENT_CURRENT('OSOBA'), 'ul. Polanki', 0);
-- these throw the below error message
INSERT INTO OSOBA (imie,nazwisko,zawod,dataUrodzenia,plec,narodowosc) VALUES ('Marcia','Frank','Architekt','19570720','0','Niemiec');
INSERT INTO ARCHITEKCI (id,styl,liczba) VALUES (IDENT_CURRENT('OSOBA'),'Nowoczesny',8);
Error:
Msg 2627, Level 14, State 1, Line 124
Violation of UNIQUE KEY constraint 'UQ_ARCHITEK_982D973E2BA18BE7'. Cannot insert duplicate key in object 'dbo.ARCHITEKCI'. The duplicate key value is ().
As Aaron mentioned the IDENT_CURRENT is not very reliable. It would be better to use an OUTPUT clause. See the following example:
DECLARE #LatestID TABLE (ID INT);
INSERT INTO #OSOBA (imie,nazwisko,zawod,dataUrodzenia,plec,narodowosc)
OUTPUT INSERTED.ID INTO #LatestID
VALUES ('Marcia','Frank','Architekt','19570720','0','Niemiec');
INSERT INTO #ARCHITEKCI (id,styl,liczba) VALUES ((SELECT ID FROM #LatestID),'Nowoczesny',8);