Inner joins with 2 foreign keys to one primary key - sql

I have a table called
branch (branchid, branchname)
and another table called transfer
transfer(tranferid, sourcebranch, destinationbranch)
both sourcebranch and destinationbranch are Fk to the branchid of of branch table.
I need to show a query that looks like this
Tranferid Source Destination
4 uk us
but all I can get is something like this
Tranferid Source Destinationid
4 uk 3
query sample
select tranferid, branch.branchname, transfer.destinationbranch
from transfer
inner join branch on branch.branchid == transfer.sourcebranch
How do I get the destination branch to show. CTE on my mind

You need to join table branch on table transfer twice so you can get the value for each column.
SELECT a.*,
b.branchName AS sourceBranchName,
c.branchName AS destinationBranchName
FROM transfer a
INNER JOIN branch b
ON a.sourcebranch = b.branchID
INNER JOIN branch c
ON a.destinationbranch = c.branchID
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins

Related

How can I take a joined table and use it to reference another table?

I've just started learning SQL and need help with an assignment question. I am asked to look through a dataset about Kickstarter campaigns. I'm asked to find the top 3 categories by amount of backers.
Here is the ER diagram:
ER diagram
In the 'Campaign' Table, there's the 'backers' column, but the 'Category' Table is only related with the Campaign through the 'Sub-Category' Table.
So far, I have been able to Join sub_category.category_id with the sub-category.category_name, but i'm not sure how to take this new Table and join it with Campaign
SELECT C.name AS category_name, SC.category_id, SC.id AS SC_id
FROM Category AS C
JOIN sub_category AS SC ON C.id = SC.category_id
Screenshot
I am hoping to have a table where there is a column for 'Category Name' and 'Backers' and then simply sort it by the number of backers
How should I go about this? Am I on the right track?
SELECT C.name AS category_name, CA.backers
FROM campaign AS CA
JOIN sub_category AS SC
ON CA.sub_category_id =SC.Id
JOIN Category AS C
ON C.id = SC.category_id
order by CA.backers
You can have multiple joins all together in one query.
Secondly there is a connection between Campaign and Sub_Category table which will help to join these two tables.
Later we can then join Category table as these two table has a connection between them based on Category_Id which is a foreign key in sub category table.
At last you can just order by based on Backers.
Let me know if you have any issue or doubt in comments.
And just to take Magnus's answer and rewrite visually, you can better see the hierarchy of the query. See how it closely resembles that of your table relationships
SELECT
C.name category_name,
CA.backers
FROM
campaign CA
JOIN sub_category SC
ON CA.sub_category_id = SC.Id
JOIN Category C
ON SC.category_id = C.id
order by
CA.backers
Notice the indentation to the table its ID is based upon from that prior to it. This way you know which column FROM connecting TO. I have found that if you list the tables in the FROM clause first to show all the HOW tables are related and ON what foreign : primary key relationships, that is the hardest part. Then its just pulling the columns you want after that.

Complex SQL Query with Dead Ends and 7 Tables

I was tasked with creating a complex query that incudes all of the data from all of the tables minus the Keys. I am having an issue with the dead end tables and how to circle back around to include the data of the connecting table. I need to select columns DivisionName, ProgramName, ProgramChairFName, ProgramChairLName, CourseID, OutcomeDescription from the listed tables.
SQL Diagram
The 'dead-ends' aren't really dead-ends. When you join all the tables by the appropriate keys, you'll get an assembly of the information you want.
Consider a really simple example:
table person
id name
1 Alice
table pet
id person_id animal
1 1 cat
table hobby
id person_id activity
1 1 dancing
Here, the two tables pet and hobby link to the person table via the person_id key.
In your thinking, "pet" could be considered a "dead-end" because it doesn't link to hobby. But it doesn't need to. The query:
SELECT name, animal, activity
FROM person
JOIN pet ON person.id = pet.person_id
JOIN hobby ON person.id = hobby.person_id;
creates the correct joins back to the person table. It's not a linear path (person -> pet -> hobby). The nature of the joins are specified by the "ON" part of the query. You can see this simple example works here: http://sqlfiddle.com/#!9/02c94b/1
So, in your case, you can have a series of JOINs:
SELECT [all the columns you want]
FROM Division d JOIN Program p
ON d.DivisionKey = p.DivisionKey
JOIN ProgramChairMap pcm
ON p.ProgramKey = pcm.ProgramKey
JOIN ProgramChair pc
ON pcm.ProgramChairKey = pc.ProgramChairKey
JOIN Course c
ON p.ProgramKey = c.ProgramKey
JOIN CourseOutcome co
ON c.CourseKey = co.CourseKey
JOIN Outcome o
ON co.OutsomeKey = o.OutcomeKey

SQL Update - Using Multiple Table Joins

Wondering if anyone can point me in the right direction please.
I Have 3 tables...
Table A -
Code, Cost1, Cost2, Cost3
Table B -
Code, ID
Table C -
ID, Price
Basically I need to update the Price Field on Table C with (Cost1+Cost2+Cost3)
from Table A.
There is no direct link between the 2 tables, but A is linked to B via Code and B is linked to C via ID.
I can write a query to display Price and the Total Cost but can't get my head around how to do the Update.
Any pointers would be extremely welcome
Thanks
Andrew
UPDATE TC
SET Price=(TA.Cost1+TA.Cost2+TA.Cost3)
FROM TableA TA
INNER JOIN TableB TB ON TA.Code=TB.Code
INNER JOIN TableC TC ON TC.ID=TB.ID
I prefer writing my more complicated joins out first and then simply updating the alias. As you can see in the example, you could comment out the top two lines and simply put in a SELECT TC.ID,TA.Cost1+TA.Cost2+TA.Cost3 and see exactly what would change.

SQL fetch multiple values on join

Hi I have an SQL table which has two tables which make reference to the same foreign key in a separate table twice... something like
SALES table
idSales idClient1 idClient2
1 1 2
CLIENT table
idClient ClientName
1 Bob
2 Mick
I want to join the SALES table to the CLIENT table and return data as follows:
idSales idClientClientName1 idClientClientName2
1 Bob Mick
Can anyone help with the SQL for this? I'm getting ambiguous column name errors on my join.
Thank you
You need to basically join table Client on table Sales twice because there are two columns on table Sales that are dependent on table Client.
SELECT a.idSales,
b.ClientName ClientName1,
c.ClientName ClientName2
FROM Sales a
INNER JOIN Client b
ON a.idClient1 = b.idClient
INNER JOIN Client c
ON a.idClient2 = c.idClient
To further gain more knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins
But when one of the columns or both columns are nullable, INNER JOIN will not give you all records from Sales because it will only select where it has atleast one match on the other table. Instead use LEFT JOIN.
I might add that in cases like this, I use table aliases that hint at what entity you are linking to in the joined table. If for example, the foreign keys were to an address table, and you had a work address, and a Home address, I would use tables aliases of h and w for the two joins. In your case, i.e.,
Selext s.idSales,
c1.ClientName ClientName1,
c2.ClientName ClientName2
From Sales s
Join Client c1
On c1.idClient = s.idClient1
Join Client c2
On c2.idClient = s.idClient2
For those beginner SQL folks who may see this question in the future, it's helpful to add in the AS words, it makes it clearer still:
SELECT
Sale.idSales,
c1.ClientName AS ClientName1,
c2.ClientName AS ClientName2
FROM
Sales AS Sale
INNER JOIN Client AS c1 ON Sale.idClient1 = c1.idClient
INNER JOIN Client AS c2 ON Sale.idClient2 = c2.idClient

Making Report From Four Tables

I am working in Oracle APEX.I am Making report from following four tables Patient History Junction and Disease but unable to make it.
I want to SELECT
Pat_Name,Pat_Age` from Patient Table
.
Treated_By,Sys_Date from History Table
and
Dis_Name from Disease Table
.There is a Junction Table between History and Disease. Below is the diagram of the above scenario.
You need to JOIN each of the tables, similar to this:
select p.pat_name,
p.pat_age,
h.treated_by,
h.sys_date,
d.dis_name
from patient p
inner join history h
on p.pat_id = h.pat_id
and p.app_id = h.app_id
left join junction j
on p.pat_id = j.pat_id
left join disease d
on j.dis_id = d.dis_id
If you need help learning join syntax, check this helpful visual explanation of joins.
Notice that I used an INNER JOIN between patient and history and joined the tables on both keys in patient. This type of join will return all matching records in both tables.
I used a LEFT JOIN on the other two tables which will return all of the patient/history data even if there is not a matching record in the other two tables. Depending on your need, you might be able to use an INNER JOIN on those tables.