SQL Multiple columns same join column - mysql

I have a table with 3 columns in my table Travel (and of course some more):
AirportFrom,
AirportTo,
AirportFound.
The columns above display ID's from airports. In the table Airports are 2 columns AirportID and AirportName.
Instead of displaying the ID's from the airports I want to display the AirportNames.
But when I use:
SELECT id
, AirportFrom
, Airports.Airportname
, AirportTo
, Airports.Airportname
, AirportFound
, Airports.Airportname
FROM Travel
LEFT
JOIN Airports
ON AirportTo = Airports.AirportID
-- LEFT JOIN Airports ON AirportFrom = Airports.AirportID
-- LEFT JOIN Airports ON AirportFound = Airports.AirportID
It only displays the airport name of the first join in every column. I want to show the airport name for each of the 3 joins

Provide multiple aliases for joined table each time you left join, and join them as you have multiple tables:
SELECT
Travel.id,
airport_to.Airportname as to_name,
airport_from.Airportname as from_name,
airport_found.Airportname as found_name,
FROM Travel
LEFT JOIN Airports airport_to ON Travel.AirportTo = airport_to.AirportID
LEFT JOIN Airports airport_from ON Travel.AirportFrom = airport_from.AirportID
LEFT JOIN Airports airport_found ON Travel.AirportFound = airport_found.AirportID
EDIT: Replace reserved words in table aliases. Thanks for the reminder!

Your query needs table aliases (for multiple joins to the same table). Then, be sure to use qualified columns names for all columns in a query. This helps you write correct queries and it helps you and other people understand what is going on. So:
SELECT t.id, t.AirportFrom, apt.Airportname,
t.AirportTo, apf.Airportname,
t.AirportFound, apfo.Airportname
FROM Travel t LEFT JOIN
Airports apt
ON t.AirportTo = apt.AirportID LEFT JOIN
Airports apf
ON t.AirportFrom = apf.AirportID LEFT JOIN
Airports apfo
ON t.AirportFound = apfo.AirportID;

Related

Getting the names of a field based on the same foreign key but different values in one statement

My brain is melting a bit with this one, please go easy I am a rookie.
I have a flights table with a flight origin(airport id from airports table) and a flight destination(also an airport id from airports table). Both fields are foreign keys of the airport id. I can get the results I need with two different selects but can I get the results using only one SELECT or do I need to rethink how I designed the database?
SELECT airports.airportName AS 'FROM'
FROM airports
INNER JOIN flights ON airports.id = flights.flightOrigin
WHERE flights.id = 1;
SELECT airports.airportName AS 'TO'
FROM airports
INNER JOIN flights ON airports.id = flights.flightDestination
WHERE flights.id = 1;
Select the airports table twice and give a different alias to each instance (like a and b):
SELECT a.airportName AS 'FROM', b.airportName AS 'TO'
FROM flights f
INNER JOIN airports a ON a.id = f.flightOrigin
INNER JOIN airports b ON b.id = f.flightDestination
WHERE f.id = 1;

Left join issue with reference table

Im having a bit of difficulty with getting user information from one place to another.
There are 3 tables dbo.gr_usersource and dbo.gr_task and dbo.gr_user
In the dbo.gr_task table a column is filled with values that match entries in dbo.gr_usersource table that has another value that corresponds to the value in the dbo.gr_user table. You could call it a reference table between dbo.gr_task and dbo.gr_user tables.
My query looks like this;
select
dbo.gr_task.task_number
, dbo.gr_task.task_name
, dbo.gr_task.task_description
from dbo.gr_task
left join dbo.gr_user AS Handler
on dbo.gr_usersource.usersource_user = Handler.user_id
and dbo.gr_task.task_handler = dbo.gr.usersource.usersource.id
The last step would be to get the column user_name from table user when the join is working.
You have missed mediator table in your join so use as per below-
SELECT dbo.gr_task.task_number,dbo.gr_task.task_name, dbo.gr_task.task_description
FROM dbo.gr_task AS gt
LEFT JOIN dbo.gr_usersource gus ON gt.task_handler=gus.usersource.id
LEFT JOIN dbo.gr_user AS gu ON gus.usersource_user=gu.user_id;
Note: If you want only matching rows in all 3 tables then you should use normal join instead of left join.
This may work for you.
Note that there are no columns from your joined tables in your select list so left joins would have no impact on your result set.
Inner joins will filter your results set even if you bring back no columns, i.e., enforce the join condition to match rows in both tables.
SELECT
t.task_number
, t.task_name
, t.task_description
FROM dbo.gr_task t
INNER JOIN dbo.gr_usersource us
ON us.usersource.id = t.task_handler
INNER JOIN dbo.gr_user u
ON u.user_id = us.usersource_user

How to create the inner query wtih 5 different tables mysql

Having 5 tables
Table a_dates = id,
Table b_types = id, a_date_id, c_type_id,
Table c_types = id, name,
Table d_profiles = id, name, profile_type
Table e_ps = id, a_date_id, d_profile_id
From a_dates Need to get b_types,...then from b_types needs c_types name,... Then compare c_types name with d_profiles name and get d_profiles id.... if equals then create a records in e_ps with a_date_id, d_profile_id.
Could any one please help me in getting the query from inner join.
I tried like, it is incomplete query
INSERT INTO e_ps(id,a_date_id,a_date_type,d_profile_id,c_id)
SELECT '',a.id,'A',dp.id,'67' FROM d_profiles dp
INNER JOIN a_dates a ON {HERE I NEED NAME MATCHING WITH c_types name} = dp.name and dp.profile_type = 'A'
INNER JOIN a_dates ON a.id = a_dates.id
LEFT OUTER JOIN e_ps eps ON eps.a_date_type = 'A' AND eps.a_date_id = a_dates.id
WHERE eps.a_date_id IS NULL
This seems to be a relatively simple JOIN:-
INSERT INTO e_ps(id, a_date_id, d_profile_id)
SELECT NULL, a_dates.id, d_profiles.id
FROM a_dates
INNER JOIN b_types ON a_dates.id = b_types.a_date_id
INNER JOIN c_types ON b.c_type_id = c.id
INNER JOIN d_profiles ON c_types.name = d_profiles.name
With joins there are several types, and I suspect you are getting confused. Briefly:-
With an INNER JOIN it looks for a match that is on BOTH tables. If no
match the no record is returned.
With a LEFT OUTER JOIN it takes a record from the table on the left
and looks for a match on the table on the right. If a match great,
but if not then it still brings a row back but the columns from the
table on the right just have values of NULL.
A RIGHT OUTER JOIN is very much the same, just with the tables
reversed (most people including me avoid using this as it has no
advantages most of the time but just makes things confusing).
With a FULL OUTER JOIN it gets the records from both side, whether
they match or not. If they match then the columns from both are
returned, if not matched then the columns from one are returned. Not
that MySQL does not support a FULL OUTER JOIN (although there are
ways to emulate it).
A CROSS JOIN joins every combination of 2 tables. These are used when
there is no common column to match on but you want all combinations.
For example if you wanted a table of all employees and all days of
the week for each employee you would cross join a table of days of
the week against a table of employees (then for useful data you might
LEFT OUTER JOIN a table of holidays to the result).

What is the difference between these two MySQL queries?

SELECT COUNT( companyId )
FROM Companies
LEFT JOIN Cities ON Cities.cityId = Companies.cityId
GROUP BY Companies.companyId;
VS
SELECT COUNT( companyId )
FROM Cities
LEFT JOIN Companies ON Cities.cityId = Companies.cityId
GROUP BY Companies.companyId;
What is the difference?
In the first query left table is Companies and in the second query Cities.
The LEFT JOIN keyword returns all rows from the left table
(table_name1), even if there are no matches in the right table
(table_name2).
FIRST QUERY
The LEFT JOIN keyword returns all rows from the Companies table
, even if there are no matches in the Cities table
SECOND QUERY
The LEFT JOIN keyword returns all rows from the Cities table
, even if there are no matches in the Companies table
Visual Representation of SQL Joins
I'm just placing a picture (self explained)
MySQL left JOIN

MySQL Multiple Joins in one query?

I have the following query:
SELECT
dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
So I am using an INNER JOIN and grabbing the image_id. So now, I want to take that image_id and turn it into images.filename from the images table.
How can I add that in to my query?
You can simply add another join like this:
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
However be aware that, because it is an INNER JOIN, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
LEFT OUTER JOIN images
ON dashboard_messages.image_id = images.image_id
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
I shared my experience of using two LEFT JOINS in a single SQL query.
I have 3 tables:
Table 1) Patient consists columns PatientID, PatientName
Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID
Table 3) Doctor consists columns DoctorID, DoctorName
Query:
SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname
FROM Appointment
LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId //have doctorId column common
LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId //have patientid column common
WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE
AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates
ORDER BY AppointmentDateTime ASC; // getting data as ascending order
I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")
Multi joins in SQL work by progressively creating derived tables one after the other.
See this link explaining the process:
https://www.interfacett.com/blogs/multiple-joins-work-just-like-single-joins/