views/ queries for multiple foreign keys referencing same primary keys - sql

Hello I have got two tables and the staff_id from the risk table is used to look up the name of the owner and contact person. I was wondering if it is possible to create a view which includes both the owner name and staff name. I tried to create a view as shown below but I could only include either owner name or contact name in the view. (For reference I am using derby). Thanks in advance.
CREATE VIEW public_view AS
SELECT r.risk_id, r.risk_name s.staff_name
FROM risk r, staff s
AND r.owner_id = s.staff_id;
CREATE TABLE STAFF
(
staff_id varchar(8) NOT NULL,
staff_name varchar(100),
staff_email_addr varchar(30),
staff_position varchar(30),
staff_sect_elem varchar(60),
CONSTRAINT pk_staff_id PRIMARY KEY (staff_id)
);
CREATE TABLE RISK
(
risk_id varchar(6) NOT NULL,
risk_name varchar(20) NOT NULL,
risk_desc varchar(20),
owner_id varchar(8),
contact_id varchar(8),
CONSTRAINT pk_risk_id PRIMARY KEY (risk_id),
CONSTRAINT fk_owner_id FOREIGN KEY (owner_id) REFERENCES STAFF(staff_id),
CONSTRAINT fk_contact_id FOREIGN KEY (contact_id) REFERENCES STAFF(staff_id)
);

Use table aliases:
select *
from RISK r
LEFT OUTER JOIN STAFF o ON r.owner_id = o.staff_id
LEFT OUTER JOIN STAFF c ON r.contact_id = c.staff_id

You were close. You need to create a table with data from both tables using a join, in this case joining on fk:
CREATE VIEW public_view AS
SELECT r.risk_id, r.risk_name s.staff_name
FROM risk r
LEFT JOIN staff s
ON r.owner_id = s.staff_id;
Left join will not pull data that is in Staff table but not in Risk table.

This is what I ended up doing
CREATE VIEW public_view1 (risk_id, risk_name, owner_name, contact_name) AS
SELECT r.risk_id, r.risk_name, o.staff_name, c.staff_name
FROM risk r
LEFT OUTER JOIN staff o ON r.owner_id = o.staff_id
LEFT OUTER JOIN staff c ON r.contact_id = c.staff_id;

Related

how Inner join work on two foreign key from single table

I am working on Bus route management system , I made two table first one is Cities and second one is route have following queries
CREATE TABLE Cities
(
ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
Name Varchar(30) not null,
)
CREATE TABLE route
(
ID NUMBER GENERATED ALWAYS AS IDENTITY(START with 1 INCREMENT by 1) PRIMARY KEY,
Name Varchar(30) not null,
from NUMBER not null,
to NUMBER NOT NULL,
CONSTRAINT FROM_id_FK FOREIGN KEY(from) REFERENCES Cities(ID),
CONSTRAINT TO_id_FK FOREIGN KEY(to) REFERENCES Cities(ID),
)
i am joining the table through inner join
select CITIES.Name
from CITIES
inner join ROUTES on CITIES.ID=ROUTES.ID
but it show single column as
Name
-----------
but i want result as
from | to
------------------------
what is possible way to do this using inner join
I suspect you need something like the following:
select r.Name, cs.Name SourceCity, cd.Name DestinationCity
from routes r
join cities cs on cs.id = r.from
join cities cd on cd.id = r.to
Hope is working for you
select CITIES.Name,ROUTES.from,ROUTES.to
from CITIES inner join ROUTES on CITIES.ID=ROUTES.ID

JOIN ON SQL syntax

I am taking my first database class and need some info on what I need to change for my script to process. Currently I have 2 tables, an "orders" table and a "customers" table and this is how they are coded.
CREATE TABLE customers (
customer_id INT ,
customer_first_name VARCHAR(20),
customer_last_name VARCHAR(20) NOT NULL,
customer_address VARCHAR(50) NOT NULL,
customer_city VARCHAR(20) NOT NULL,
customer_state CHAR(2) NOT NULL,
customer_zip CHAR(5) NOT NULL,
customer_phone CHAR(10) NOT NULL,
customer_fax CHAR(10),
CONSTRAINT customers_pk
PRIMARY KEY (customer_id)
);
CREATE TABLE order (
order_id INT NOT NULL,
customer_id INT NOT NULL,
order_date DATE NOT NULL,
shipped_date DATE,
employee_id INT,
CONSTRAINT orders_pk
PRIMARY KEY (order_id),
CONSTRAINT orders_fk_customers
FOREIGN KEY (customer_id) REFERENCES customers (customer_id),
CONSTRAINT orders_fk_employees
FOREIGN KEY (employee_id) REFERENCES employees (employee_id)
);
My script to join these two tables together is as follows:
SELECT or.order_id, or.order_date, or.customer_city,
cu.customer_first_name, cu.customer_last_name
FROM orders or INNER JOIN customers cu
ON or.customer_first_name = cu.customer_first_name
AND or.customer_last_name = cu.customer_last_name;
Now obviously, I know it is incorrect and may have multiple errors, so be gentle. I would love to know what I can do to make it work. Please advise.
Two things:
Don't use or as an alias. That's a reserved word.
Join by the foreign key.
The query should look like:
SELECT o.order_id, o.order_date, cu.customer_city,
cu.customer_first_name, cu.customer_last_name
FROM orders o
INNER JOIN customers cu
on o.customer_id = cu.customer_id
You can join your tables on the ID numbers, and you won't have to worry about what happens when multiple people have the same name.
Use this instead:
FROM orders ord INNER JOIN customers cu
ON ord.order_id = cu.customer_id
Your select statement can remain as it is. I also re-aliased according to the comment from Error_2646.
Using a field that is a primary key in one of your tables is also better practice than using non-key fields, when possible.

Trying to do a three table join displaying all columns

I am trying to do a three table join to display all columns. Only two of the tables have a key in common. Below is the code for the tables I already have:
CREATE TABLE Faculty (
FacultyID int,
FirstName varchar(30),
LastName varchar(30),
EMail varchar(60),
BirthDate DATE,
Numbr_Courses int,
PRIMARY KEY (FacultyID)
);
CREATE TABLE Courses(
CourseID int,
CourseDisc varchar(4),
CourseNum varchar(4),
NumbrCred varchar(1),
FirstYrOffered int,
CourseTitle varchar(75),
PRIMARY KEY (CourseID)
);
CREATE TABLE Faculty_Courses(
InstanceID int,
FacultyID int,
CourseDisc varchar(4),
CourseNum varchar(4),
CourseTitle varchar(75),
PRIMARY KEY (InstanceID),
FOREIGN KEY (FacultyID) REFERENCES Faculty(FacultyID)
);
The two tables that have the same key is Faculty and Faculty_Course. I have attempted one peice of code that only gave me back an error. I guess I am having real trouble understanding how to do proper code for joining tables. My attempted code is below:
SELECT Faculty.*, Faculty_Courses.*
FROM Faculty INNER JOIN Courses
ON Faculty.FacultyID=Faculty_Courses.FacultyID
This gave me back the following error:
ERROR 1066 (42000): Not unique table/alias: 'Faculty'
Any help will be appreciated.
I would change your Faculty_Courses table:
CREATE TABLE Faculty_Courses(
InstanceID int,
FacultyID int,
CourseID int,
PRIMARY KEY (InstanceID),
FOREIGN KEY (FacultyID) REFERENCES Faculty(FacultyID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
And then join all three tables together:
SELECT F.*, FC.*, C.*
FROM Faculty F
INNER JOIN Faculty_Courses FC ON F.FacultyID = FC.FacultyID
INNER JOIN Courses C ON C.CourseID = FC.CourseID
You probably only really want some of the columns from F (Faculty) and C (Courses) and can mostly ignore the FC columns as they are just used for mapping between F and C
I'm surprised your factory_courses table doesn't have a reference to courses.
Either way, with your current query, you are selecting from faculty and courses but aliasing faculty_courses -- you cannot do that. This is what your current query should look like:
select *
from faculty f
join faculty_courses fc on f.facultyid = fc.facultyid
To join the 3rd table, if you had a courseid in your faculty_courses table, perhaps something like this:
select *
from faculty f
join faculty_courses fc on f.facultyid = fc.facultyid
join courses c on fc.courseid = c.courseid
A Visual Explanation of SQL Joins
You're doing a join on two tables without actually linking two columns from those tables; joining Faculty and Courses using columns from Faculty and Faculty_Courses.
Since no column exists with unique values linking Courses with any other table, you cannot perform a join with Courses.
So you should join Faculty and Faculty_courses:
SELECT Faculty.*, Faculty_Courses.*
FROM Faculty INNER JOIN Faculty_Courses
ON Faculty.FacultyID=Faculty_Courses.FacultyID

Write a query using INNER JOIN AND OR

I have a form and an insert button and when i click on the button - the fields goes in to these tables (i didn't put here all the fields because they are not important for my question).
The Tables:
CREATE TABLE SafetyAct (
SafetyAct_id int identity(1,1),
Username varchar(50),
SafetyType_id int,
constraint pk_SafetyAct_id
primary key (SafetyAct_id),
constraint fk_Users_SafetyAct
foreign key(Username)
references Users(Username)
on delete cascade
)
CREATE TABLE Product (
Product_id int identity(1,1) primary key,
SafetyAct_id int,
Cause_id int,
constraint fk_SafetyAct_Product
foreign key(SafetyAct_id)
references SafetyAct(SafetyAct_id)
on delete cascade,
constraint fk_Cause_Product
foreign key(Cause_id)
references Cause(Cause_id)
on delete cascade
)
CREATE TABLE SafetyIntervention (
SafetyIntervention_id int identity(1,1) primary key,
SafetyAct_id int,
Cause_id int,
constraint fk_SafetyAct_SafetyIntervention
foreign key(SafetyAct_id)
references SafetyAct(SafetyAct_id)
on delete cascade,
constraint fk_Cause_SafetyIntervention
foreign key(Cause_id)
references Cause(Cause_id)
on delete cascade
)
CREATE TABLE Cause (
Cause_id int primary key,
Cause_name varchar(80)
)
I want to write a query that shows the fields - SafetyAct_id and Cause_name.
in the Cause_name field i have a problem because i want that the query will show me the cause name drom the Product table or from the SafetyIntervension table (of course to connect it to the Cause table because i have only the cause_id - foriegn key in these tables) and i don't know how to write INNER JOIN and OR at the same query.
I am new with this so plase be patient.
Thank you!
SELECT SA.SafetyAct_id,
C.Cause_name
FROM SafetyAct SA
LEFT JOIN Product P
ON SA.SafetyAct_id = P.SafetyAct_id
LEFT JOIN SafetyIntervention SI
ON SA.SafetyAct_id = SI.SafetyAct_id
LEFT JOIN Cause C
ON ISNULL(P.Cause_id,SI.Cause_id) = C.Cause_id
An or is easy. So, based on Lamak's code:
SELECT SA.SafetyAct_id,
C.Cause_name
FROM SafetyAct SA LEFT JOIN
Product P
ON SA.SafetyAct_id = P.SafetyAct_id LEFT JOIN
SafetyIntervention SI
ON SA.SafetyAct_id = SI.SafetyAct_id LEFT JOIN
Cause C
ON C.Cause_id = P.Cause_id OR C.Cause_Id = SI.Cause_id;
--------------------------------^
You can just use OR in the ON condition.
However, it is often challenging for a SQL engine (SQL Server included) to optimize a join when the on condition includes or or functions on the columns used for the join. Hence, the following is often more efficient:
SELECT SA.SafetyAct_id,
COALESCE(Cp.Cause_name, Csi.Cause_Name) as Cause_Name
FROM SafetyAct SA LEFT JOIN
Product P
ON SA.SafetyAct_id = P.SafetyAct_id LEFT JOIN
SafetyIntervention SI
ON SA.SafetyAct_id = SI.SafetyAct_id LEFT JOIN
Cause Cp
ON Cp.Cause_id = P.Cause_id LEFT JOIN
Cause Csi
ON Csi.Cause_Id = SI.Cause_id;
If only some of the records have a cause of either type, then add:
WHERE Cp.Cause_Id IS NOT NULL OR Csi.Cause_Id IS NOT NULL;

How to create relationship between two non primary key entity in SQL Server

I have few tables where I need to link Patient card ID (PID) of table patient where primary key is patient_id with the PID field of other tables... how can I do that? help!
you can join them like
SELECT *
FROM [Patient] p
INNER JOIN [OtherTable] ot
ON p.pid = ot.patient_id;
You can use Foreign Keys
CREATE TABLE T
(
any_primary_key INT PRIMARY KEY,
[other attributes],
patient_id,
FOREIGN KEY (patiend_id) REFERENCES Patients.patient_id
)
Where Patients is a table that has the original patient_id which has to be declared as unique.