So I'm working on a SQL and I keep getting errors and I have triple checked it and still haven't come up with a reason as to why the queries aren't showing up correctly. I'm using Microsoft SQL Server. These are the errors that I'm currently getting:
Msg 1767, Level 16, State 0, Line 2
Foreign key 'FK_PatientID' references invalid table 'Patient'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.
Msg 208, Level 16, State 1, Line 2
Invalid object name 'TreatmentDetails'.
Code:
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'Hospital')
DROP DATABASE [Hospital]
GO
CREATE DATABASE [Hospital]
GO
USE Hospital
GO
CREATE TABLE [dbo].[Physician]
(
PhysicianID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Specialty VARCHAR(30) NOT NULL,
GraduationDate DATE NOT NULL,
CONSTRAINT [PK_PhysicianID] PRIMARY KEY (PhysicianID)
);
GO
CREATE TABLE [dbo].[TreatmentDetails]
(
TreatmentID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
StartDateTime DATE NOT NULL,
EndDateTime DATE NULL,
Results VARCHAR(30),
CONSTRAINT [PK_TreatmentID] PRIMARY KEY (TreatmentID),
CONSTRAINT [FK_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
CREATE TABLE [dbo].[Patient]
(
PatientID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
DateOfBirth DATE NOT NULL,
CONSTRAINT [PK_PatientID] PRIMARY KEY (PatientID),
);
GO
CREATE TABLE [dbo].[AdmissionDate]
(
AdmissionID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
AdmissionDate DATE NOT NULL,
DischargeDate DATE NULL,
CONSTRAINT [PK_AdmissionID] PRIMARY KEY (AdmissionID),
CONSTRAINT [FK_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
INSERT INTO TreatmentDetails VALUES (1, 12345, 1234, '2014-4-5', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (2, 12346, 1235, '2013-5-6', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (3, 12347, 1236, '2012-7-8', '2014-9-10', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (4, 12348, 1237, '2011-9-10', '2013-11-12', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (5, 12349, 1238, '2010-11-12', NULL, 'NOT DONE')
INSERT INTO Physician VALUES (12345, 'Will', 'Smith', 'Surgeon', '2014-5-9');
INSERT INTO Physician VALUES (12346, 'Jim', 'Carey', 'Pediatrictian', '2013-2-4');
INSERT INTO Physician VALUES (12347, 'Adam', 'Sandler', 'Immunologist', '2012-6-12');
INSERT INTO Physician VALUES (12348, 'Seth', 'Rogan', 'Neurologist', '2010-9-19');
INSERT INTO Physician VALUES (12349, 'James', 'Bond', 'Dermatologist', '2011-5-2');
INSERT INTO Patient VALUES (1234, 'Christopher', 'Thompson', '1989-7-9');
INSERT INTO Patient VALUES (1235, 'Mac', 'Miller', '1970-9-5');
INSERT INTO Patient VALUES (1236, 'Abraham', 'Lincoln', '1988-1-22');
INSERT INTO Patient VALUES (1237, 'George', 'Washington', '1965-2-8');
INSERT INTO Patient VALUES (1238, 'Franklin', 'Roosevelt', '1992-5-19');
INSERT INTO AdmissionDate VALUES (001, 12345, 1234,'2014-2-9', NULL);
INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-15-9');
INSERT INTO AdmissionDate VALUES (003, 12347, 1236,'2014-3-7', '2014-4-9');
INSERT INTO AdmissionDate VALUES (004, 12348, 1237, '2014-8-6', NULL);
INSERT INTO AdmissionDate VALUES (005, 12349, 1238, '2014-5-5', NULL);
GO
USE Hospital
SELECT * FROM Physician
SELECT * FROM Patient
SELECT * FROM AdmissionDate
SELECT * FROM TreatmentDetails
SELECT Patient.PatientID, Patient.FirstName, Patient.LastName, Patient.DateOfBirth, AdmissionDate.AdmissionDate, AdmissionDate.DischargeDate, Physician.Specialty
FROM Patient, AdmissionDate, Physician
WHERE AdmissionDate IS NOT NULL
ORDER BY Patient.LastName, Patient.FirstName, AdmissionDate.AdmissionDate
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NOT NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
You have incorrect order of creating tables.
You are creating foreign keys with same name in different tables.
You are inserting data in tables in incorrect order.
You have provided incorrect date format. Default format is YYYY-MM-DD
and you provide INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-15-9'); 2014-15-9 this is to change.
Here is working script:
USE master
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'Hospital')
DROP DATABASE [Hospital]
GO
CREATE DATABASE [Hospital]
GO
USE Hospital
GO
CREATE TABLE [dbo].[Physician]
(
PhysicianID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Specialty VARCHAR(30) NOT NULL,
GraduationDate DATE NOT NULL,
CONSTRAINT [PK_PhysicianID] PRIMARY KEY (PhysicianID)
);
GO
CREATE TABLE [dbo].[Patient]
(
PatientID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
DateOfBirth DATE NOT NULL,
CONSTRAINT [PK_PatientID] PRIMARY KEY (PatientID),
);
GO
CREATE TABLE [dbo].[TreatmentDetails]
(
TreatmentID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
StartDateTime DATE NOT NULL,
EndDateTime DATE NULL,
Results VARCHAR(30),
CONSTRAINT [PK_TreatmentDetails_TreatmentID] PRIMARY KEY (TreatmentID),
CONSTRAINT [FK_TreatmentDetails_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_TreatmentDetails_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
CREATE TABLE [dbo].[AdmissionDate]
(
AdmissionID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
AdmissionDate DATE NOT NULL,
DischargeDate DATE NULL,
CONSTRAINT [PK_AdmissionDate_AdmissionID] PRIMARY KEY (AdmissionID),
CONSTRAINT [FK_AdmissionDate_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_AdmissionDate_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
INSERT INTO Physician VALUES (12345, 'Will', 'Smith', 'Surgeon', '2014-5-9');
INSERT INTO Physician VALUES (12346, 'Jim', 'Carey', 'Pediatrictian', '2013-2-4');
INSERT INTO Physician VALUES (12347, 'Adam', 'Sandler', 'Immunologist', '2012-6-12');
INSERT INTO Physician VALUES (12348, 'Seth', 'Rogan', 'Neurologist', '2010-9-19');
INSERT INTO Physician VALUES (12349, 'James', 'Bond', 'Dermatologist', '2011-5-2');
INSERT INTO Patient VALUES (1234, 'Christopher', 'Thompson', '1989-7-9');
INSERT INTO Patient VALUES (1235, 'Mac', 'Miller', '1970-9-5');
INSERT INTO Patient VALUES (1236, 'Abraham', 'Lincoln', '1988-1-22');
INSERT INTO Patient VALUES (1237, 'George', 'Washington', '1965-2-8');
INSERT INTO Patient VALUES (1238, 'Franklin', 'Roosevelt', '1992-5-19');
INSERT INTO TreatmentDetails VALUES (1, 12345, 1234, '2014-4-5', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (2, 12346, 1235, '2013-5-6', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (3, 12347, 1236, '2012-7-8', '2014-9-10', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (4, 12348, 1237, '2011-9-10', '2013-11-12', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (5, 12349, 1238, '2010-11-12', NULL, 'NOT DONE')
INSERT INTO AdmissionDate VALUES (001, 12345, 1234,'2014-2-9', NULL);
INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-9-15');
INSERT INTO AdmissionDate VALUES (003, 12347, 1236,'2014-3-7', '2014-4-9');
INSERT INTO AdmissionDate VALUES (004, 12348, 1237, '2014-8-6', NULL);
INSERT INTO AdmissionDate VALUES (005, 12349, 1238, '2014-5-5', NULL);
GO
USE Hospital
SELECT * FROM Physician
SELECT * FROM Patient
SELECT * FROM AdmissionDate
SELECT * FROM TreatmentDetails
SELECT Patient.PatientID, Patient.FirstName, Patient.LastName, Patient.DateOfBirth, AdmissionDate.AdmissionDate, AdmissionDate.DischargeDate, Physician.Specialty
FROM Patient, AdmissionDate, Physician
WHERE AdmissionDate IS NOT NULL
ORDER BY Patient.LastName, Patient.FirstName, AdmissionDate.AdmissionDate
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NOT NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
Related
I have 2 tables that look like this where I want to query how many scholarships (from Tuition table) each department (from Student table) has distributed:
I am thinking a join is necessary but am not sure how to do so.
Create tables
create table students (
sid int auto_increment primary key,
name varchar(100),
email varchar(100),
department varchar(100)
);
create table tutions (
id int auto_increment primary key,
sid int,
cost int,
scholarships int,
duedate timestamp default current_timestamp
);
Sample data
insert into students (name, email, department)
values
('John Doe', 'john#abc.xyz', 'B'),
('Jane Doe', 'jane#abc.xyz', 'A'),
('Jack Doe', 'jack#abc.xyz', 'C'),
('Jill Doe', 'jill#abc.xyz', 'B');
insert into tutions (sid, cost, scholarships)
values
(1, 1000, 2),
(2, 1000, 1),
(3, 1000, 7),
(4, 1000, 2);
Query (department-wise total scholarships)
SELECT department, sum(scholarships) as scholarships
FROM students s
JOIN tutions t ON s.sid = t.sid
GROUP BY department
Output
Running SQL Fiddle
Not sure It's something you want? And not sure scholarships is a number or name of scholarship? So I doubt it's a name as varchar string type.
### dummy record
CREATE TABLE students (
psu_id INTEGER PRIMARY KEY,
firstname VARCHAR NOT NULL,
lastname VARCHAR NOT NULL,
email VARCHAR NOT NULL,
department VARCHAR NOT NULL
);
CREATE TABLE tuition (
tuition_id INTEGER PRIMARY KEY,
student_id INTEGER NOT NULL,
semeter_cost INTEGER NOT NULL,
scholarships VARCHAR NOT NULL,
due_date DATE NOT NULL
);
INSERT INTO students VALUES (1, 'John', 'Hello', 'Jonh#email.com', 'Engineering');
INSERT INTO students VALUES (2, 'Bella', 'Fuzz', 'Bella#email.com', 'Computer');
INSERT INTO students VALUES (3, 'Sunny', 'World', 'Sunny#email.com', 'Science');
INSERT INTO tuition VALUES (1, 1, 4000, 'first_class_en', '2022-05-09' );
INSERT INTO tuition VALUES (2, 2, 3000, 'nobel', '2022-05-09' );
INSERT INTO tuition VALUES (3, 3, 5000, 'hackathon', '2022-05-09' );
INSERT INTO tuition VALUES (4, 1, 4500, 'second_class_en', '2022-05-09' );
-----------------
### query
SELECT s.department, count(t.scholarships)
FROM students s
JOIN tuition t
ON s.psu_id = t.student_id
GROUP BY s.department
### output
department, total_scholarships
Computer|1
Engineering|2
Science|1
I need to group two columns, one of them with an average, AVG() inside an LISTAGG().
I have the following code:
CREATE OR REPLACE VIEW countryTimes AS
SELECT
LISTAGG(claOL.odCode||'-'||(AVG(claOL.timeCla) GROUP BY(claOl.timeCla))) WITHIN GROUP (ORDER BY c.cCode) AS ProvaTempsMig,
c.cDescription AS País,
c.cCode AS CodiPaís
FROM countries c
JOIN athletes a ON c.cCode = a.country
JOIN classificationOL claOL ON a.idCode = claOL.idAth;
But this throws this error:
ORA-00907: missing right parenthiesis erecho 00907. 00000 - "missing right parenthesis" *Cause: *Action:
I'm using Oracle.
UPDATE:
What I need to do is create a view where appears cCode, cDescription and a last column with the AVG of all the times for a single country. So I need to create from multiple rows, a single row for each country.
Code:
CREATE TABLE Countries (
cCode VARCHAR(5) NOT NULL,
cdescription VARCHAR(100) NOT NULL,
CONSTRAINT couPK PRIMARY KEY (cCode)
);
CREATE TABLE athletes (
idCode NUMBER NOT NULL,
Name VARCHAR(200) NOT NULL,
Surname VARCHAR(200) NOT NULL,
country VARCHAR(5) NOT NULL,
CONSTRAINT athPK PRIMARY KEY (idCode),
CONSTRAINT countryFK FOREIGN KEY (country) REFERENCES Countries (cCode)
);
CREATE TABLE olympicDisciplines (
oCode VARCHAR(10) NOT NULL,
odName VARCHAR(200) NOT NULL,
discipline VARCHAR(200) NOT NULL,
CONSTRAINT olympicPK PRIMARY KEY (oCode)
);
CREATE TABLE classificationOL(
idAth NUMBER NOT NULL,
odCode VARCHAR(10) NOT NULL,
timeCla INTEGER,
CONSTRAINT classifPK PRIMARY KEY (idAth, odCode),
CONSTRAINT claAthFK FOREIGN KEY (idAth) REFERENCES athletes (idCode),
CONSTRAINT claDFK FOREIGN KEY (odCode) REFERENCES olympicDisciplines (oCode)
);
UPDATE 2:
Data:
INSERT INTO Countries VALUES ('UK', 'United Kingdom');
INSERT INTO Countries VALUES ('AND', 'Andorra');
INSERT INTO Countries VALUES ('FR', 'France');
INSERT INTO athletes VALUES (1, 'Jack', 'Johnson', 'UK');
INSERT INTO athletes VALUES (2, 'Pau', 'Márquez', 'AND');
INSERT INTO athletes VALUES (3, 'Pierre', 'Dubois', 'FR');
INSERT INTO athletes VALUES (4, 'Christophe', 'Dubois', 'FR');
INSERT INTO athletes VALUES (5, 'Adolphe', 'Moreau', 'FR');
INSERT INTO olympicDisciplines VALUES ('ATH', 'Athletics', 'Athletics');
INSERT INTO olympicDisciplines VALUES ('CYC', 'Cycling', 'Cycling');
INSERT INTO olympicDisciplines VALUES ('CCC', 'Cycling CC', 'Cross Country Cycling');
INSERT INTO classificationOL VALUES (1, 'ATH', 120);
INSERT INTO classificationOL VALUES (2, 'ATH', 119);
INSERT INTO classificationOL VALUES (3, 'CCC', 38);
INSERT INTO classificationOL VALUES (4, 'CCC', 37);
INSERT INTO classificationOL VALUES (5, 'ATH', 122);
Reading your first UPDATE, if you're allowed to, you can transform your tables to object to solve your necessity, instead of using LISTAGG(). I'll show you:
CREATE TYPE average AS OBJECT(
name VARCHAR(200),
avgerageTime NUMBER);
CREATE TYPE results AS TABLE OF average;
CREATE TYPE countriesResults AS OBJECT(
cName VARCHAR(100),
cCode VARCHAR(5),
classifications results
);
CREATE VIEW countriesAverages OF countriesResults
WITH OBJECT OID (coName)
AS
SELECT c.cdescription, c.ccode,
CAST (MULTISET (SELECT
olympicDisciplines.name, avg(classificationOL.timeCla)
FROM athletes a, countries, classificationOL, olympicDisciplines
WHERE countries.cCode = c.cCode
AND a.idCode = classificationOL.idAth
AND a.country = countries.cCode
AND olympicdisciplines.oCode = classificationOL.oCode
GROUP BY olympicdisciplines.odName) AS results )
FROM countries c;
Everything runs fine. End part gives an ORA-02291 error. Not sure what would be causing that error, since I thought all the code was running well. This was made in Oracle SQL developer, the error message is ORA-02291. I hope someone can give me an answer. Please help me.
Code:
CREATE TABLE comm_customer
(
Customer_Id int NOT NULL,
Customer_Name VARCHAR(50) NOT NULL,
Address VARCHAR(255) NOT NULL,
Billing_Address VARCHAR(255) NOT NULL,
city VARCHAR(255) NOT NULL,
country VARCHAR(255) NOT NULL,
phone INT NOT NULL,
primary key(Customer_id)
);
CREATE TABLE comm_orders
(
order_Id INT NOT NULL,
Customer_id INT NOT NULL,
order_date DATE NOT NULL,
amount DECIMAL(5,2) NOT NULL,
Order_status VARCHAR(20) NOT NULL,
primary key(order_id),
FOREIGN KEY (customer_id ) REFERENCES comm_customer(customer_id)
);
CREATE TABLE comm_products
(
product_id INT NOT NULL,
product_name VARCHAR(255) NOT NULL,
product_price decimal(5,2) NOT NULL,
product_quantity decimal(5,2) NOT NULL,
product_status VARCHAR(255) NOT NULL,
customer_id int NOT NULL,
primary key(product_id),
FOREIGN KEY (customer_id ) REFERENCES comm_customer(customer_id)
);
CREATE TABLE comm_shipments
(
shipment_id INT NOT NULL,
order_id INT NOT NULL,
shipment_date DATE NOT NULL,
PRIMARY KEY (shipment_id),
FOREIGN KEY (order_id ) REFERENCES comm_orders(order_id)
);
CREATE TABLE comm_shopping_cart
(
orderdetails_id INT NOT NULL,
order_id INT NOT NULL,
product_id int NOT NULL,
quantity int NOT NULL,
price decimal(5,2),
primary key(orderdetails_id),
FOREIGN KEY (order_id ) REFERENCES comm_orders(order_id),
FOREIGN KEY (product_id ) REFERENCES comm_products(product_id)
);
--For Table Comm_customer
insert into comm_customer values(1011, 'John', '48 Maple Heights Road', '48 Maple Heights Road', 'Toronto', 'Canada', 9988766779);
insert into comm_customer values(1012, 'James', '32 St.Jordan Cressent', '32 St.Jordan Cressent', 'Chennai', 'India', 9988722779);
insert into comm_customer values(1013, 'Anderson', '5 Thornway Street', '#1755 JBS Colony', 'Surat', 'India', 9988123779 );
insert into comm_customer values(1014, 'Jose', '88 Greenbelt Drive', '#1983 ABS Nagar', 'Mumbai', 'India', 9988766885 );
insert into comm_customer values(1015, 'Leo', '#1765 XSX Nagar', '#10993 ACD Nagar', 'Hoshiarpur', 'India', 9955466779 );
--For Table Comm_products:
INSERT into comm_products values(01, 'XI Phone', 250, 4, 'checked out', 1015);
INSERT into comm_products values(02, 'Book', 120, 2, 'not checked out', 1011);
INSERT INTO comm_products values(03, 'Vegetable',100, 5, 'not checked out', 1012);
INSERT into comm_products values(04, 'Biscuits', 250, 1, 'checked out', 1013);
INSERT into comm_products values(05, 'Shampoo', 500, 2, 'not checked out', 1014);
--For table Comm_orders:
insert into comm_orders values(11, 1014, '2020-MAY-01', 500, 'checked out');
insert into comm_orders values(12, 1011, '2019-JUL-18', 140, 'not checked out');
insert into comm_orders values(13, 1013, '2020-JAN-31', 170, 'checked out');
insert into comm_orders values(14, 1012, '2019-FEB-15', 120, ' not checked out');
insert into comm_orders values(15, 1011, '2018-JUN-21', 600, 'checked out');
--For table comm_shippments:
insert into comm_shipments values(001, 13, '2020-FEB-05');
insert into comm_shipments values(002, 15, '2018-JUL-01');
insert into comm_shipments values(003, 12, '2019-07-25');
insert into comm_shipments values(004, 11, '2020-MAY-05');
insert into comm_shipments values(005, 14, '2019-FEB-25');
--For table comm_shopping_cart:
insert into comm_shopping_cart values(701, 01, 11, 4, 250);
insert into comm_shopping_cart values(702, 02, 12, 3, 120);
insert into comm_shopping_cart values(704, 03, 13, 6, 100);
insert into comm_shopping_cart values(703, 04, 14, 2, 250);
insert into comm_shopping_cart values(705, 05, 15, 1, 500);
OK, so you say the statement that is erroring out is this
insert into comm_shopping_cart values(701, 01, 11, 4, 250);
I'd strongly urge you to list the columns in your insert statement. That helps to document things so that someone doesn't have to constantly refer up to the table definition to see what order columns are defined in. And it means that your statements won't suddently fail in the future when you add new columns.
insert into comm_shopping_cart( orderdetails_id,
order_id,
product_id,
quantity,
price)
values(701,
01,
11,
4,
250);
OK, so having done that, the error is that the parent key isn't found. Your actual error message should include the name of the constraint which would tell you which column is the problem. You haven't given us that information so we'll have to figure it out. There are two foreign keys on comm_shopping_cart, the order_id and the product_id. So which one doesn't exist?
You're trying to insert a row with an order_id of 01 (I don't understand why you're putting leading 0's in a numeric column). But you only have order_id values in the comm_orders table between 11 and 15.
You're also trying to insert a row with a product_id of 11. But you only have product_id values between 1 and 5 in your comm_products table. So both foreign key constraints would fail.
My guess is that you intended to specify an order_id of 11 and a product_id of 1 in your insert statement and reversed the order of the columns. Since you didn't include the column list in your insert statement, you made it much harder on yourself to debug the problem because your insert statements aren't self-documenting. Had you specified the column list, you could also have listed the columns in whatever order you wanted so if you wanted to specify the product_id before the order_id you could have.
With the tables below, I am trying to answer this question and I have no idea how to answer it:
"Show the sum of HoursWorked for each Type of OWNER but exclude services of employees who have ExperienceLevel of Junior and exclude any Type with less than three members."
CREATE TABLE OWNER
(
OwnerID Int NOT NULL IDENTITY (1,1) PRIMARY KEY,
OwnerName Char(30) NOT NULL,
OwnerEmail VarChar(100) NULL,
OwnerType Char(15) NOT NULL,
);
CREATE TABLE PROPERTY
(
PropertyID Int NOT NULL IDENTITY(1,1) PRIMARY KEY,
PropertyName Char(30) NOT NULL,
Street Char(20) NOT NULL,
City Char(25) NOT NULL,
State Char(10) NOT NULL,
Zip Char(5) NOT NULL,
OwnerID Int NOT NULL,
CONSTRAINT PROP_OWN_FK FOREIGN KEY(OwnerID)
REFERENCES OWNER(OwnerID),
);
CREATE TABLE GG_EMPLOYEE
(
EmployeeID Int NOT NULL IDENTITY(1,1) PRIMARY KEY,
LastName Char(35) NOT NULL,
FirstName Char(35) NOT NULL,
CellPhone Char(20) NOT NULL,
ExperienceLevel Char(25) NOT NULL,
);
CREATE TABLE SERVICE
(
PropertyID Int NOT NULL,
EmployeeID Int NOT NULL,
ServiceDate Char(15) NOT NULL,
HoursWorked Char(5) NOT NULL,
CONSTRAINT SERVICE_PK PRIMARY KEY(PropertyID, EmployeeID, ServiceDate),
CONSTRAINT SER_PRO_FK FOREIGN KEY(PropertyID)
REFERENCES PROPERTY(PropertyID),
CONSTRAINT SER_GG_EMP_FK FOREIGN KEY(EmployeeID)
REFERENCES GG_EMPLOYEE(EmployeeID),
);
INSERT INTO OWNER
VALUES ('Mary Jones', 'Mary.Jones#somewhere.com', 'Individual');
INSERT INTO OWNER
VALUES('DT Enterprises', 'DTE#dte.com', 'Corporation');
INSERT INTO OWNER
VALUES('Sam Douglas', NULL, 'Individual');
INSERT INTO OWNER
VALUES('UNY Enterprises', 'UNYE#unye.com', 'Corporation');
INSERT INTO OWNER
VALUES('Doug Samuels', 'Doug.Samuels#somewhere.com', 'Individual');
INSERT INTO PROPERTY
VALUES('Eastlake Building', '123 Eastlake', 'Seattle', 'WA', '98119');
INSERT INTO PROPERTY
VALUES('Elm St Apts', '4 East Elm', 'Lynwood', 'WA', '98223');
INSERT INTO PROPERTY
VALUES('Jefferson Hill', '42 West 7th St', 'Bellevue', 'WA', '98007');
INSERT INTO PROPERTY
VALUES('Lake View Apts', '1265 32nd Avenue', 'Redmond', 'WA', '98054');
INSERT INTO PROPERTY
VALUES('Kodak Heights Apts', '65 32nd Avenue', 'Rochester', 'NY', '14604');
INSERT INTO PROPERTY
VALUES('Private Residence', '1456 48th St', 'Bellevue', 'WA', '98007');
INSERT INTO PROPERTY
VALUES('Private Residence', '1567 51st St', 'Bellevue', 'WA', '98007');
INSERT INTO PROPERTY
VALUES('Private Residence', '718 151st St', 'Rochester', 'NY', '14604');
INSERT INTO GG_EMPLOYEE
VALUES('Smith', 'Sam', '206-254-1234', 'Master');
INSERT INTO GG_EMPLOYEE
VALUES('Evanston', 'John', '206-254-2345', 'Senior');
INSERT INTO GG_EMPLOYEE
VALUES('Murray', 'Dale', '206-254-3456', 'Junior');
INSERT INTO GG_EMPLOYEE
VALUES('Murphy', 'Jerry', '585-545-8765', 'Master');
INSERT INTO GG_EMPLOYEE
VALUES('Fontaine', 'Joan', '206-254-4567', 'Senior');
INSERT INTO SERVICE VALUES('2015-05-05', '4.50');
INSERT INTO SERVICE VALUES('2015-05-08', '2.75');
INSERT INTO SERVICE VALUES('2015-05-08', '4.50');
INSERT INTO SERVICE VALUES('2015-05-19', '3.00');
INSERT INTO SERVICE VALUES('2015-05-12', '7.50');
INSERT INTO SERVICE VALUES('2015-05-10', '2.50');
INSERT INTO SERVICE VALUES('2015-05-19', '2.50');
INSERT INTO SERVICE VALUES('2015-05-15', '2.75');
If someone could please help me, that would be great!
Columns OwnerID in Property Table and PropertyId and EmployeeID in Service table are making trouble for you.
Following are the reason for that.
1) All the mentioned columns are set as NOT NULL. So these column
always expect value for every insert.
2) Also,In 'service' table ,columns PropertyId and EmployeeID are
part of composite primary key. Primary key doesn't allow NULL values.
3)Once you handle the points 1 and 2,You can make the insert by
mentioning columns in your INSERT query,like below
INSERT INTO PROPERTY (PropertyName,Street,City,[State],Zip)
VALUES('Eastlake Building', '123 Eastlake', 'Seattle', 'WA', '98119');
INSERT INTO [SERVICE] (ServiceDate,HoursWorked)
VALUES('2015-05-05', '4.50');
http://sqlfiddle.com/#!6/3ea54
You need to say who is the owner, the insert doesnt know that.
here I assing every property to owner = 1
INSERT INTO PROPERTY VALUES('Eastlake Building', '123 Eastlake', 'Seattle', 'WA', '98119', 1);
INSERT INTO PROPERTY VALUES('Elm St Apts', '4 East Elm', 'Lynwood', 'WA', '98223', 1 );
INSERT INTO PROPERTY VALUES('Jefferson Hill', '42 West 7th St', 'Bellevue', 'WA', '98007', 1);
INSERT INTO PROPERTY VALUES('Lake View Apts', '1265 32nd Avenue', 'Redmond', 'WA', '98054', 1);
INSERT INTO PROPERTY VALUES('Kodak Heights Apts', '65 32nd Avenue', 'Rochester', 'NY', '14604', 1);
INSERT INTO PROPERTY VALUES('Private Residence', '1456 48th St', 'Bellevue', 'WA', '98007', 1);
INSERT INTO PROPERTY VALUES('Private Residence', '1567 51st St', 'Bellevue', 'WA', '98007', 1);
INSERT INTO PROPERTY VALUES('Private Residence', '718 151st St', 'Rochester', 'NY', '14604', 1);
hey luke problem is that in insert query values count is not matching with column count of tables.
if u want to use advantage of Auto increment property write insert query with column names.
and column 'OwnerID' in PROPERTY table and 'EmployeeID' in SERVICE table can not be null as you restricted in table creation.
Using Table aliases, list the first name, last name and start date of students enrolled on the java fundamentals module:
I am having some trouble when running the query below.
SELECT stu.StudFName, stu.StudLName, enrol.StartDate
From Student stu
INNER JOIN Enrolment enrol
ON stu.StudID = enrol.StudID
INNER JOIN Module mod
ON enrol.ModCode = mod.ModCode
WHERE mod.ModName = 'Java Fundamentals'
Structure:
CREATE TABLE Student
(StudID INTEGER PRIMARY KEY,
StudFName VARCHAR(10) NOT NULL,
StudLName VARCHAR(10) NOT NULL,
DoB DATE NOT NULL,
Sex CHAR(1) NOT NULL CHECK (Sex IN ('M', 'F')),
Email VARCHAR(30) UNIQUE);
CREATE TABLE Staff
(StaffID INTEGER PRIMARY KEY,
Title VARCHAR(4) CHECK (Title IN ('Prof', 'Dr', 'Mr', 'Mrs', 'Miss')),
StaffFName VARCHAR(10) NOT NULL,
StaffLName VARCHAR(10) NOT NULL,
Email VARCHAR(30) UNIQUE,
Department VARCHAR(25) DEFAULT 'Not Assigned',
Extension INTEGER CHECK (Extension BETWEEN 0001 AND 9999));
CREATE TABLE Module
(ModCode CHAR(4) PRIMARY KEY,
ModName VARCHAR(25) NOT NULL,
ModCredits INTEGER NOT NULL CHECK (ModCredits IN (15, 30, 45, 60)),
ModLevel CHAR(3) NOT NULL CHECK (ModLevel IN ('UG1', 'UG2', 'UG3', 'MSc')),
ModLeader INTEGER NOT NULL,
Foreign Key (ModLeader) REFERENCES Staff (StaffID));
CREATE TABLE Enrolment
(ModCode CHAR(4) NOT NULL,
StudID INTEGER NOT NULL,
StartDate DATE NOT NULL,
PRIMARY KEY (ModCode, StudID),
Foreign Key (StudID) REFERENCES Student (StudID),
Foreign Key (ModCode) REFERENCES Module (ModCode));
The answer is... there is no trouble with your query.
It works just fine.
Check here
INSERT INTO Student (StudID, StudFName, StudLName, DoB, Sex, Email) VALUES
(1, 'Jack', 'Black', TO_DATE('2015/01/01', 'yyyy/mm/dd'), 'M', 'jack#email.com');
INSERT INTO Student (StudID, StudFName, StudLName, DoB, Sex, Email) VALUES
(2, 'Andrew', 'Wiggin', TO_DATE('2015/01/01', 'yyyy/mm/dd'), 'M', 'andrew#email.com');
INSERT INTO Student (StudID, StudFName, StudLName, DoB, Sex, Email) VALUES
(3, 'Bob', 'Marley', TO_DATE('2015/01/01', 'yyyy/mm/dd'), 'M', 'bob#email.com');
INSERT INTO Staff (StaffID, Title, StaffFName, StaffLName, Email, Extension) VALUES
(1, 'Prof', 'Joe', 'Smith', 'stuff#emal.com', 0001);
INSERT INTO Module (ModCode, ModName, ModCredits, ModLevel, ModLeader) VALUES
(1, 'Java Fundamentals', 30, 'UG1', 1);
INSERT INTO Module (ModCode, ModName, ModCredits, ModLevel, ModLeader) VALUES
(2, 'C# Fundamentals', 15, 'UG2', 1);
INSERT INTO Enrolment (ModCode, StudID, StartDate) VALUES
(1, 1, TO_DATE('2015/01/01', 'yyyy/mm/dd'));
INSERT INTO Enrolment (ModCode, StudID, StartDate) VALUES
(1, 2, TO_DATE('2015/01/02', 'yyyy/mm/dd'));
INSERT INTO Enrolment (ModCode, StudID, StartDate) VALUES
(2, 3, TO_DATE('2015/01/03', 'yyyy/mm/dd'));
-------------------------------------------------------------
SELECT stu.StudFName, stu.StudLName, enrol.StartDate
From Student stu
INNER JOIN Enrolment enrol ON stu.StudID = enrol.StudID
INNER JOIN Module mod ON enrol.ModCode = mod.ModCode
WHERE mod.ModName = 'Java Fundamentals'
Result
STUDFNAME STUDLNAME STARTDATE
----------------------------------------
Jack Black January, 01 2015
Andrew Wiggin January, 02 2015