dbTalk Databases Forums  

Trying to join three tables

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Trying to join three tables in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
JJ297
 
Posts: n/a

Default Trying to join three tables - 08-24-2007 , 11:30 AM






Having problems joining three tables. I only want the Title field but
need them to give me the correct data.

Here are my three tables and their fields.

1. Titles
TitleID
Title
[description]


2. Classifications
ClassificationID
[Description]

3. Titleclassification
ClassificationID
TitleID

This is my stored procedure thus far but getting incorrect syntax
error.

select Titles.Title

Quote:
From Titles
Inner Join Titleclassification on classifications.classificationid =
titleclassification.classificationid
Join titlecassification.titleid = titles.titleid



Reply With Quote
  #2  
Old   
Erland Sommarskog
 
Posts: n/a

Default Re: Trying to join three tables - 08-24-2007 , 04:46 PM






JJ297 (nc297 (AT) yahoo (DOT) com) writes:
Quote:
Having problems joining three tables. I only want the Title field but
need them to give me the correct data.

Here are my three tables and their fields.

1. Titles
TitleID
Title
[description]


2. Classifications
ClassificationID
[Description]

3. Titleclassification
ClassificationID
TitleID

This is my stored procedure thus far but getting incorrect syntax
error.

select Titles.Title
From Titles
Inner Join Titleclassification on classifications.classificationid =
titleclassification.classificationid
Join titlecassification.titleid = titles.titleid
The form for a three-way join would be:

SELECT ...
FROM tbl1 t1
JOIN tbl2 t2 ON t1.somecol = t2.somecol
JOIN tbl3 t3 ON t2.someothercol = t3.someothercol

This pattern should give you some idea to write the query. Notice that I
use aliases. This helps to make the query less verbose. If you use the
table names as prefixes, you can easily lose the sight of the forest
for all the trees.

However, I think your correct query needs to use exists instead:

SELECT T.TitleID
FROM Titles T
WHERE EXISTS (SELECT *
FROM Titleclassifications TC
JOIN Classifications C
ON TC.ClassificationID = C.ClassificationID
WHERE TC.TitleID = T.TitleID)


Else you will get a lot of duplicates.



--
Erland Sommarskog, SQL Server MVP, esquel (AT) sommarskog (DOT) se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.