How can I get 3 tables INNER JOIN in MS SQL Server - sql-server

From the specialist table, retrieve the first name, last name and contact number for the people that provide care to penguins from the species table.
There are 3 tables: tbl_specialist, tbl_species, tbl_care
I need help trying to INNER JOIN the tables to display First, Last, And Contact for penguins.
SELECT specialist_fname, specialist_lname, specialist_contact
FROM ((tbl_specialist
INNER JOIN tbl_species ON species_care = tbl_species.species_care)
INNER JOIN tbl_care ON care_id = tbl_care.care_id)
WHERE species_name = 'penguin'
;

It's a bit difficult without seeing the exact schema of the tables, but your syntax for the subquery is a bit off and you need to alias columns that are found in multiple tables in a JOIN statment. Try rewriting your SQL like this:
SELECT spl.specialist_fname, spl.specialist_lname, spl.specialist_contact
FROM tbl_specialist spl
INNER JOIN tbl_species s
ON spl.species_care = s.species_care
INNER JOIN tbl_care c
ON s.care_id = c.care_id
WHERE s.species_name = 'penguin'
I'm obviously inferring which tables certain columns come from in the join, but hopefully you get the idea.

I figured it out thank you.
SELECT specialist_fname, specialist_lname, specialist_contact
FROM ((tbl_specialist
INNER JOIN tbl_care ON tbl_care.care_specialist = tbl_specialist.specialist_id)
INNER JOIN tbl_species ON tbl_species.species_care= tbl_care.care_id)
WHERE species_name = 'penguin'
;

Related

MS SQL Server trouble with JOIN

I'm new to SQL and need a push in the right direction.
I currently have a working SQL query accessing 3 tables in a database, and I need to add a JOIN using a 4th table, but the syntax escapes me. To simplify, what I have now is:
SELECT
t1_col1, t1_col2, t2_col1, t2_col2, t3_col1
FROM
table1, table2, table3
WHERE
{some conditions}
ORDER BY
t1_col1 ASC;
What I need to do is to add a LEFT OUTER JOIN selecting 2 columns from table4 and have ON t1_field1 = t4_field1, but whatever I try, I'm getting syntax errors all over the place. I don't seem to understand the correct syntax.
I tried
SELECT *
FROM table1
LEFT OUTER JOIN table2;
which has no errors, but as soon as I start SELECTing columns and adding conditions, I get stuck.
I would greatly appreciate any assistance with this.
You do not specify the join criteria. Those would be in your WHERE clause under "some conditions". So, I will make up so that I can show syntax. The syntax you show is often termed "old". It has been discouraged for 15 years or more in the SQL Server documentation. Microsoft consistently threatens to stop recognizing the syntax. But, apparently they have not followed through on that threat.
The syntax errors you are getting occur because you are mixing the old style joins (comma separated with WHERE clause) with the new style (LEFT OUTER JOIN) with ON clauses.
Your existing query should be changed to something like this. The tables are aliased because it makes it easier to read and is customary. I just made up the JOIN criteria.
SELECT t1_col1, t1_col2, t2_col1, t2_col2, t3_col1
FROM table1 t1
INNER JOIN table2 t2 ON t2.one_ID = t1.one_ID
INNER JOIN table3 t3 ON t3.two_ID = t2.two_ID
LEFT OUTER JOIN table4 t4 ON t4.three_ID = t3.three_ID
I hope that helps with "a push in the right direction."
You may also want to read this post that explains the different ways to join tables in a query. What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?
Also for the record the "OLD STYLE" of joining tables (NOT RECOMMENDED) would look like this (but do NOT do this - it is a horrible way to write SQL). And it does not work for left outer joins. Get familiar with using the ...JOIN...ON... syntax:
SELECT t1_col1, t1_col2, t2_col1, t2_col2, t3_col1
FROM table1 t1, table2 t2, table3 t3
LEFT OUTER JOIN table4 t4 ON t4.three_ID = t3.three_ID
WHERE
t2.one_ID = t1.one_ID
AND t3.two_ID = t2.two_ID

SQL Server to SalesForce Linked Server Nightmare

I am getting inconsistent results from joining Linked Servers. It's something that should be relatively simple... but has taken me hours to get this figured out. I am using SQL Server 2014 and the CData ODBC Driver to Join to SalesForce. I'm not doing anything fancy just trying to perform standard CRUD operations but again and again it seems that when ever I filter these linked server tables that sometimes results do not produce.
My current and main issue right now is I am having difficulty JOINING two Linked tables to two Local tables. If I remove one of the Linked tables from the join results are produced. But whenever I add two linked tables to the joins it produces and empty record set.
And yes all the related identifiers exist so it really is an issue with the Linked Server. Here are the three variations that I've tried:
SELECT * FROM Offer_Interest oi
INNER JOIN Offer o ON oi.Offer_ID_SQL = o.Offer_ID_SQL
INNER JOIN OPENQUERY([TR-SF-PROD], 'SELECT Id, OFFER_ID_SQL__C FROM Offer__c') osf ON o.Offer_ID_SQL =osf.OFFER_ID_SQL__C
INNER JOIN Interest i ON oi.Interest_ID_SQL = i.Interest_ID_SQL
INNER JOIN OPENQUERY([TR-SF-PROD], 'SELECT INTEREST_ID_SQL__C, Id FROM Interest__c') isf ON i.Interest_ID_SQL =isf.Interest_ID_SQL__c
WHERE o.PrimaryContact_ID_SQL = 2803
I've also tried without OPENQUERY:
SELECT * FROM FROM Offer_Interest oi
INNER JOIN Offer o ON oi.Offer_ID_SQL = o.Offer_ID_SQL
INNER JOIN [TR-SF-PROD].[CDataSalesforce].[Salesforce].[Offer__c] osf ON o.Offer_ID_SQL =osf.OFFER_ID_SQL__C
INNER JOIN Interest i ON oi.Interest_ID_SQL = i.Interest_ID_SQL
INNER JOIN [TR-SF-PROD].[CDataSalesforce].[Salesforce].[Interest__c] isf ON i.Interest_ID_SQL =isf.Interest_ID_SQL__c
WHERE o.PrimaryContact_ID_SQL = 2803
And Lastly I've also created Synonyms to the Linked Server tables. All of these work using the same filter or WHERE CLAUSE if I run them seperately although the linked server tables seem buggy if I filter them without OPENQUERY.
This is my first experience Linking a Server to SQL Server so anyone with experience in this or what the issue may be would be greatly appreciated!
Not the answer I was hoping as it should just work. But a temp fix I came up with is stuffing the linked server values I need into Temp Tables then joining on the temp tables, which worked... but of course this adds time onto the execution of the overall stored procedure so it is definitely not the ideal solution. If anyone has a better idea please still answer!!
IF EXISTS(SELECT [NAME] FROM tempdb.sys.tables WHERE [NAME] like '#TempOffer%') BEGIN
DROP TABLE #TempOffer;
END;
SELECT * INTO #TempOffer FROM OPENQUERY([TR-SF-PROD], 'SELECT Id, OFFER_ID_SQL__C FROM Offer__c')
IF EXISTS(SELECT [NAME] FROM tempdb.sys.tables WHERE [NAME] like '#TempInterest%') BEGIN
DROP TABLE #TempInterest;
END;
SELECT * INTO #TempInterest FROM OPENQUERY([TR-SF-PROD], 'SELECT INTEREST_ID_SQL__C, Id FROM Interest__c')
SELECT * FROM Offer_Interest oi
INNER JOIN Offer o ON oi.Offer_ID_SQL = o.Offer_ID_SQL
INNER JOIN #TempOffer osf ON o.Offer_ID_SQL =osf.OFFER_ID_SQL__C
INNER JOIN Interest i ON oi.Interest_ID_SQL = i.Interest_ID_SQL
INNER JOIN #TempInterest isf ON i.Interest_ID_SQL =isf.Interest_ID_SQL__c
WHERE o.PrimaryContact_ID_SQL = 2803

Inner Join to Same Table Twice on same column

I'm having a problem with a SQL Server query trying to join a view with another view twice
SELECT
FAC.*
FROM
ViewFacturacionDiaria_Test AS FAC
INNER JOIN
ViewInformacionRepresentantes AS REP
ON REP.RepIDTabacal = FAC.Vendedor
INNER JOIN
ViewInformacionRepresentantes AS REP2
ON REP2.RepIDCtayOrden = FAC.Vendedor
WHERE
FecCpbte BETWEEN '2015-11-28' AND '2015-11-30'
In the "FAC" view I have sales information, in the other one I have a specific group of sales person which I want to filter from the main view.
I would like to understand why the query is returning an empty resultset.
Sorry, I cannot comment. But I believe Peter is right in his comment. Since you are using 2 inner joins they both need to return results. Are you expecting both joins to find a match?
Try this and see which column is null. That is the join that is resulting in no returned rows.
SELECT
FAC.Vendedor
,REP.RepIDTabacal
,REP2.RepIDCtayOrden
FROM
ViewFacturacionDiaria_Test AS FAC
LEFT JOIN
ViewInformacionRepresentantes AS REP ON
REP.RepIDTabacal = FAC.Vendedor
LEFT JOIN
ViewInformacionRepresentantes AS REP2 ON
REP2.RepIDCtayOrden = FAC.Vendedor
WHERE
FecCpbte BETWEEN '2015-11-28' AND '2015-11-30'

Complex SQL Join

I am fairly new to SQL joins, but I have a tricky issue here. I have tried to resolve this on my own, and searched as well, but unsuccessful.
I have two primary SQL tables
CustProfile
ClientID || ClientName
CustTransaction
CorpID || DivID || DeptID
I need to display my output as follows:
`CorpID` `CorpIDClientName` `DivID` `DivIDName` `DeptID` `DeptIDName`
CustTransaction.CorpID join on CustProfile.ClientID to get `CorpIDClientName`
CustTransaction.DivID join on CustProfile.ClientID to get `DivIDName`
CustTransaction.DeptID join on CustProfile.ClientID to get `DeptIDName`
I hope someone can provide the join query. Thanks in advance
try this one:
SELECT a.CorpID,
b.ClientName AS CorpIDClientName,
a.DivID,
c.ClientName AS DivIDName,
a.DeptID,
d.ClientName AS DeptIDName
FROM CustTransaction a
INNER JOIN CustProfile b
on a.CorpID = b.ClientID
INNER JOIN CustProfile c
on a.DivID = c.ClientID
INNER JOIN CustProfile d
on a.DeptID = d.ClientID
Am I understanding correctly? You have Corporations, Divisions, and Departments all stored within the CustProfile table together.
So you are only joining the 2 different tables, but you need to join those 2 tables 3 separate times to get each of the different types of customer (Corp or Div or Dept)
If that's the case, what you need to do is alias the table that you are including multiple times so you can join it as if it were 3 separate tables, one for corps, one for divisions, and one for departments.
I'm not sure if the syntax would be the same in MSSQL, but for most SQL databases your join query would look something like this:
SELECT corps.ClientID CorpID, corps.ClientName CorpIDClientName,
divs.ClientID DivID, divs.ClientName DivIDName,
depts.ClientID DeptID, depts.ClientName DeptIDName
FROM CustProfile corps, CustProfile divs, CustProfile depts, CustTransaction t
WHERE t.CorpID = corps.ClientID
AND t.DivID = divs.ClientID
AND t.DeptID = depts.ClientID
That should, I think, more or less do what you want...

Multiple Joins in TSQL

I am trying to JOIN multiple tables to the same value in a table. So I have the table ActivityPartyBase and it has a column PartyId. I want to join COntactId in ContactBase table to PartyId and AccountId in AccountBase table to PartyId. This is the code I am using and it doesn't return anything. If I only join one it works. Any ideas?
SELECT DISTINCT Appointment.ScheduledStart, ActivityPartyBase.ActivityId
, Appointment.ActivityId AS Expr1, ActivityPartyBase.ScheduledStart AS Expr2
, Appointment.Subject, ActivityPartyBase.PartyId, ContactBase.ContactId
, ContactBase.FullName
FROM Appointment
INNER JOIN ActivityPartyBase
ON Appointment.ActivityId = ActivityPartyBase.ActivityId
INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId
LEFT OUTER JOIN ContactBase ON ActivityPartyBase.PartyId = ContactBase.ContactId
ORDER BY Appointment.ScheduledStart DESC
Your inner joins are filtering out results because there is no corresponding record on the joined table. I've always found the easiest way to debug is to "Select *" and use all LEFT JOINs. This will show you everything in your tables that relates to your main table; you should be able to look at your data and figure out what table is missing a record easily at that point.
To confirm that this is just a naming convention mismatch,
INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId
Are PartyID and AccountId the PK/FK?
Given this...
FROM Appointment
INNER JOIN ActivityPartyBase ON Appointment.ActivityId = ActivityPartyBase.ActivityId
INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId
LEFT OUTER JOIN ContactBase ON ActivityPartyBase.PartyId = ContactBase.ContactId
... you state this works (?) ...
FROM Appointment
INNER JOIN ActivityPartyBase ON Appointment.ActivityId = ActivityPartyBase.ActivityId
/* INNER JOIN AccountBase ON ActivityPartyBase.PartyId = AccountBase.AccountId */
/* LEFT OUTER JOIN ContactBase ON ActivityPartyBase.PartyId = ContactBase.ContactId */
Since the LEFT OUTER JOIN won't explicitly cause no results, that won't be your problem. Since the INNER JOIN will cause what you're seeing, we can only deduce that the join condition is incorrect.
In other words, ActivityPartyBase.PartyId is not equal to AccountBase.AccountID.
Are you sure there is data in all three tables in the inner join?
I'm guessing one of your INNER JOINs isn't picking up any data. Start with all 3 joins, then take out one of the joins at a time see which one breaks it. Then look at your join conditions and see which column isn't returning a record.
SOunds to me as if the tables are mutually exclusive. If it is ione table it is not inthe other (poor design). Try left joins to both tables.

Resources