Trouble executing multiple left joins in query? - sql

I have four tables where I am trying to left join the 2nd-4th to the one on the left in this picture. From left to right:
1st table (jobs) is a table of jobs
2nd table (applications_jobs) is a bridge table to link jobs and application IDs
3rd table (applications) is applications
4th table (candidates) is candidates based on those applications
I want to get some columns from 1st table (jobs) and 4th table (candidates). I want to get job name (name) and status (status) columns from jobs table. I want to get first name (first_name) and last name (last_name) from candidates table.
Here's what I've tried:
SELECT
name, status, first_name, last_name
FROM
jobs, candidates
left join
applications_jobs aj on jobs.job_id = id
left join
applications a on aj.job_id = a.id
left join
candidates c on a.candidate_id = c.id
but get a error:
ERROR: invalid reference to FROM-clause entry for table "applications_jobs"
HINT: There is an entry for table "applications_jobs", but it cannot be referenced
from this part of the query.
any ideas?

The items you are selecting should be identified by the table they are coming from when you are performing joins, though it is not always necessary if the tables don't share column names. By writing it out, it would help to prevent the confusion you're having with the FROM clause.
The FROM clause can only be from a single table. In this case, it would be your 'jobs' table. Also, to properly reference your columns in your query, the first join should be application_jobs aj ON aj.job_id = jobs.id, and your second join should be applications a ON aj.application_id = a.id.
SELECT
"jobs".name, "jobs".status, "c".first_name, "c".last_name
FROM
jobs
left join
applications_jobs aj on aj.job_id = jobs.id
left join
applications a on aj.application_id = a.id
left join
candidates c on a.candidate_id = c.id
If you are still getting NULLs for the first and last names, Then you don't have candidates that have applications for that specific job. If you want to omit results that would otherwise be NULL, you can do an INNER JOIN on candidates so that it only returns records that exist on both sides of the equation.

Related

SQL query wrong index when where on join

I have a query with joins that is not using the index that would be the best match and I am looking for help to correct this.
I have the following query:
select
equipment.name,purchaselines.description,contacts.name,vendors.accountNumber
from purchaselines
left join vendors on vendors.id = purchaselines.vendorId
left join contacts on contacts.id = vendors.contactId
left join equipment on equipment.id = purchaselines.equipmentId
where contacts.id = 12345
The table purchaselines has an index on the column vendorId, which is the proper index to use. When the query is run, I know the value of contacts.id which is joined to vendors.contactId which is joined to purchaselines.vendorId.
What is the proper way to run this query? Currently, no index is used on the table purchaselines.
If you are intending to query a specific contact, I would put THAT first since that is the primary basis. Additionally, you had left-joins to the other tables (vendors, contacts, equipment). So by having a WHERE clause to the CONTACTS table forces the equation to become an INNER JOIN, thus REQUIRING.
That said, I would try to rewrite the query as (also using aliases for simplified readability of longer table names)
select
equipment.name,
purchaselines.description,
contacts.name,
vendors.accountNumber
from
contacts c
join vendors v
on c.id = v.contactid
join purchaselines pl
on v.id = pl.vendorid
join equipment e
on pl.equipmentid = e.id
where
c.id = 12345
Also notice the indentation of the JOINs helps readability (IMO) to see how/where each table gets to the next in a more hierarchical manner. They are all regular inner JOIN context.
So, the customer ID will be the first / fastest, then to vendors by that contact ID which should optimize the join to that. Then, I would expect the purchase lines to have an index on vendorid optimizing that. And finally, the equipment table on ITs PK.
FEEDBACK Basic JOIN clarification.
JOIN is just the explicit statement of how two tables are related. By listing them left-side and right-side and the join condition showing on what relationship is between them is all.
Now, in your data example, each table is subsequently nested under the one prior. It is quite common though that one table may link to multiple other tables. For example an employee. A customer could have an ethnicity ID linking to an ethnicity lookup table, but also, a job position id also linking to a job position lookup table. That might look something like
select
e.name,
eth.ethnicity,
jp.jobPosition
from
employee e
join ethnicitiy eth
on e.ethnicityid = eth.id
join jobPosition jp
on e.jobPositionID = jp.id
Notice here that both ethnicity and jobPosition are at the same hierarchical level to the employee table scenario. If, for example, you wanted to further apply conditions that you only wanted certain types of employees, you can just add your logical additional conditions directly at the location of the join such as
join jobPosition jp
on e.jobPositionID = jp.id
AND jp.jobPosition = 'Manager'
This would get you a list of only those employees who are managers. You do not need to explictily add a WHERE condition if you already include it directly at the JOIN/ON criteria. This helps keeping the table-specific criteria at the join if you ever find yourself needing LEFT JOINs.

Getting repeats of output, possibly doing a join wrong?

I'm having an issue where I'm getting some incorrect values in my output. I am binding the below highlighted table column with the circled column down the bottom. The service_id on the highlighted column is what is unique, but I need to bind the booking_id to retrieve the info (if that makes sense. What I end up getting is the top table where I get repeats, or the price is wrong. I should be getting only 5 lines in the top table.
Here's my code. I suspect I might be doing the join wrong?
SELECT bad.agent as Agents,
dog.SUPPLIER as SUPPLIER,
bad.status as TheStatus,
country.analysis_master1 as Country,
ftb.booking_actual_retail as BookingActualRetail,
ftb.Booking_Actual_Cost as BookingCost,
ftb.Booking_Actual_Retail_inc as BookingRetailINC,
fts.Service_Id,
fts.Service_Actual_Retail_inc as ServiceActualCostInc,
Product.SERVICE,
Product.SL_STATUS as SLSTATUS,
cat.name as Product2,
bad.LAST_SERVICE_DATE as Servicedate,
bad.LW_DATE as LWDATE,
ftb.Entered_Date as DATEENTERED,
ftb.Booking_Pax as PEOPLE,
ftb.Booking_Children as KIDS,
bad.TRAVELDATE as TRAVELDATE,
bad.FULL_REFERENCE
from BHD bad
inner join FTB on bad.FULL_REFERENCE = ftb.booking_reference
inner join FTS on FTB.Booking_Id = fts.Booking_Id
inner join DRM Country on bad.agent = country.code
inner join BSL Product on bad.BHD_ID = Product.BHD_ID
inner join SRV cat on Product.SERVICE = cat.CODE
inner join OPT dog on Product.OPT_ID = dog.OPT_ID
where bad.STATUS = 'IV' AND bad.FULL_REFERENCE = 'LTIT129488'
UPDATE:
Ok, so it looks like this join here causes the multiple outputs:
inner join FTS on FTB.Booking_Id = fts.Booking_Id
I have included the two tables, their headers, and sample data
You have somewhere put the join for the service or supplier in the wrong way.. Please check this line again.
inner join SRV cat on Product.SERVICE = cat.CODE
UPDATED SOLUTION :
As per your updated screenshots, I found the issue...
you have joined like this.
inner join FTB on bad.FULL_REFERENCE = ftb.booking_reference
In this join, your one table has single record against booking reference while another have multiple records against booking refrence. Thats why you are getting the multiple records in the output.
Remove this join and your problem will be solved. If you really want the data from this table then you can select in other way like using outer apply etc.

Join two tables in SQL Report Builder with mutiple conditions

I am using SQL Report Builder 2016.
I have 2 tables, named assets and DepreciationInfo,
following is the structure of these tables.
Table Assets:
ID|Name|Cost|Prior Dep|Prior Dep Period|Use Prior|
values would be like
123|Name|10000|4000|06/03/2014|True|
Table DepreciationInfo:
ID|EndDate|CurrentDepreciation|AccumulatedDepreciation|CarryingValue|Monthly|
values would be like
123|2020-04-30 00:00:00.000|2000|5000|5000|0/1|
I want to achieve following;
I want to select id from table assets, and will show all fields mentioned above from table assets along with fileds from table dep info based on "ID" , Column "ID" is same in both tables.
I am successful in getting all values when Id is common in both table using below mentioned query.
SELECT
Assets.ID
,Assets.Name
,Assets.Cost
,Assets.Prior Dep
,Assets.Prior Dep Period
,Assets.Use Prior
,DepreciationInfo.EndDate
,DepreciationInfo.CurrentDepreciation
,DepreciationInfo.AccumulatedDepreciation
,DepreciationInfo.CarryingValue
,DepreciationInfo.DepID
,DepreciationInfo.Monthly
FROM
Assets
INNER JOIN DepreciationInfo
ON Assets.AssetID = DepreciationInfo.AssetID
where DepreciationInfo.EndDate=#EndDate and DepreciationInfo.Monthly=0
What i want is that i want to show all results from table asset whether or not such id existed in table DepreciationInfo.
I tried all outer joins and result is same, it is showing number of records with Inner and Outer join.
Any help would be appreciated.
Change your inner join to a left join and you will see all results from table asset whether or not a corresponding assetid value exists in table DepreciationInfo. The only issue here is that the query will still be limited by your two filters in the where clause. I suggest you change them to filter off of fields in the asset table if possible:
SELECT
Assets.ID
,Assets.Name
,Assets.Cost
,Assets.Prior Dep
,Assets.Prior Dep Period
,Assets.Use Prior
,DepreciationInfo.EndDate
,DepreciationInfo.CurrentDepreciation
,DepreciationInfo.AccumulatedDepreciation
,DepreciationInfo.CarryingValue
,DepreciationInfo.DepID
,DepreciationInfo.Monthly
FROM
Assets
Left JOIN DepreciationInfo
ON Assets.AssetID = DepreciationInfo.AssetID
where Asset.EndDateorOtherCorrespondingDateValue=#EndDate and Asset.MonthlyorOtherCorrespondingValue=0
Move your where into the join and change to left join
SELECT
Assets.ID
,Assets.Name
,Assets.Cost
,Assets.Prior Dep
,Assets.Prior Dep Period
,Assets.Use Prior
,DepreciationInfo.EndDate
,DepreciationInfo.CurrentDepreciation
,DepreciationInfo.AccumulatedDepreciation
,DepreciationInfo.CarryingValue
,DepreciationInfo.DepID
,DepreciationInfo.Monthly
FROM
Assets
left JOIN DepreciationInfo
ON Assets.AssetID = DepreciationInfo.AssetID
and DepreciationInfo.EndDate=#EndDate
and DepreciationInfo.Monthly=0
Returns all assets and the matches to depreciation based on you ON conditions.
You cannot have left joined objects in your where clause or you convert that left join into an inner join (because the nulls are eliminated).

Viewing Data from two tables while linking multiple tables in SQL

I am trying to set up a view in a database I want to see all the data in the PERSON table and three columns from the NON_PERSONNEL table for a program from the PROGRAM table. This is what I am trying now, the query runs without errors but doesnt give me any results. All 4 of the tables listed below are imperative to derive the answer
SELECT
person.*,
non_personnel.description,
non_personnel.amount
FROM
person,
non_personnel,
personnel_role,
programs
WHERE
person.person_id = personnel_role.person_id
AND personnel_role.program_id = programs.program_id
AND programs.program_id = non_personnel.program_id
AND programs.program_name = 'Fake Program'
you need to use left join, so you get all persons but description and amount can be NULL if that person doesn't have records in other tables
Also use explicit join syntax.
SELECT person.*, non_personnel.description, non_personnel.amount
FROM person
left join personnel_role
ON person.person_id = personnel_role.person_id
left join programs
ON personnel_role.program_id = programs.program_id
AND programs.program_name = 'Fake Program'
left join non_personnel
ON programs.program_id = non_personnel.program_id
This really depends on your schema and the data in the tables. The way you have it written now means that only records that match in every table (according to your WHERE conditions) are passed into the result set.
This means that you have to have all program_id's in your programs table that you want returned in the results ALSO in your non_personnel table. They must also ALL be in your personnel_role table. And all person_ids in your personnel_role table must be in the person table. You get no results back, so this is probably not what you meant to write.
My guess is that you want to use a LEFT OUTER JOIN here. LEFT OUTER JOIN says "Take all records from one table and ONLY records from the joined table that meet the criteria in your ON statement".
Because you are wanting information based on a particular Program, chances are you want to start with that table:
SELECT person.*,
non_personnel.description,
non_personnel.amount
FROM
programs
LEFT OUTER JOIN personnel_role ON
programs.program_id = personnel_role.program_id
LEFT OUTER JOIN person ON
personnel_role.person_id = person.person_id
LEFT OUTER JOIN non_personnel
programs.program_id = non_personnel.program_id
WHERE
programs.program_name = 'Fake Program'
This is a bit of an assumption since I have no idea what your schema is or how your data is built, but I'm betting it's what you are after.
What this FROM clause says is:
1. Take all records from Program (where program_name = 'fake program') and only reocrds from personnel_role that share the same program_id
2. Take only the records from person where the person_id matches the records we just got from the personnel_role table
3. Take only the records from non_personnel where it shares a program_id with the results from the program table.

SQL like clause is not returning any results

I have following query, but it doesn't return any results for where clauses, even when there is row with that kind of name what is queried. If I remove where clause, then all records in Company table which have OfficeLocation table are returned. What is wrong in my query?
SELECT c.*
FROM [MyDb].[dbo].[Company] AS c
INNER JOIN [MyDb].[dbo].[CompanyOfficeLocation] AS col ON c.Id = col.CompanyId
INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON ol.Id = col.OfficeLocationId
WHERE ol.Name like '%Actual Name In This Table%';
Table structure :
Company
Id
etc ...
CompanyOfficeLocation
CompanyId
OfficeLocationId
OfficeLocation
Id
etc ...
Two things for a record to show up given your query:
The OfficeLocation you specified (given the ol.Name value) must have an Id value that is used by a record in the CompanyOfficeLocation table in its OfficeLocationId.
The CompanyOfficeLocation record that you got in #1 must have a CompanyId that exists in the Company table.
If any of those two criteria are not met, then no records will show up in your query result. The INNER JOIN is essentially an 'AND' clause. If a record could not be related to at least one INNER JOINed table, then that record will not show up at all.
If you want a record to show up despite not having any related records in the joined tables, you may want to consider using OUTER JOINs. A RIGHT JOIN in your case to be exact.
I do not find any mistake however I'd suggest you switch the columns after ON when joining to maintain standards.
Instead of - INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON ol.Id = col.OfficeLocationId
Do - INNER JOIN [MyDb].[dbo].[OfficeLocation] AS ol ON col.OfficeLocationId = ol.Id