2

I am writing a query to join 3 tables, I have the following tables:

  • Apn [ID, QualHolderID, RecvDate, Barcode]
  • QualHolder [ID, Surname, FullName, DOB, ResCountryID, Gender]
  • Country [ID, Name]
  • Gender [ID, Name]

I wrote the following SQL statement to retrieve the data:

SELECT 
    a.QualHolderID, b.FullName, b.Surname, d.Name, b.DOB, b.ResCountryID, a.RecvDate
FROM
    dbo.Apn a 
INNER JOIN 
    dbo.QualHolder b ON a.QualHolderID = b.ID 
JOIN
    dbo.QualHolder c 
INNER JOIN 
    dbo.Gender d ON c.Gender = d.ID 
WHERE
    b.ResCountryID = 48

But now I get the following error:

Msg 102, Level 15, State 1, Line 9
Incorrect syntax near 'ID'.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
kya
  • 1,798
  • 8
  • 35
  • 61
  • 2
    I would recommend to use **more meaningful alias** for your tables! Just using `a, b, c` is confusing and not helpful. I would use `a` for `Apn`, `qh` for `QualHolder`, `g` for `Gender` etc. - those aliases are much clearer and more obvious to anyone reading and studying your query – marc_s Feb 18 '14 at 09:11

3 Answers3

1

I think that the correct query is:

 SELECT a.QualHolderID, b.FullName, b.Surname, d.Name, b.DOB, b.ResCountryID, a.RecvDate
 FROM dbo.Apn a 
 INNER JOIN dbo.QualHolder b ON a.QualHolderID = b.ID 
 INNER JOIN dbo.Gender c ON b.Gender = c.ID 
 WHERE b.ResCountryID = 48
Ganz
  • 187
  • 5
0

You don't need to join dbo.QualHolder table two times. Try it this way:

SELECT a.qualholderid, 
       b.fullname, 
       b.surname, 
       d.name, 
       b.dob, 
       b.rescountryid, 
       a.recvdate 
FROM   dbo.apn a 
       INNER JOIN dbo.qualholder b 
               ON a.qualholderid = b.id 
       INNER JOIN dbo.gender d 
               ON b.gender = d.id 
WHERE  b.rescountryid = 48 
Hawk
  • 5,060
  • 12
  • 49
  • 74
slavoo
  • 5,798
  • 64
  • 37
  • 39
0

Your problem is here = b.ID JOIN use following query and execute.

SELECT a.QualHolderID, b.FullName, b.Surname, d.Name, b.DOB, b.ResCountryID, a.RecvDate
FROM (dbo.Apn a INNER JOIN dbo.QualHolder b ON a.QualHolderID = b.ID) 
INNER JOIN dbo.Gender d ON b.Gender = d.ID 
WHERE b.ResCountryID = 48
Shell
  • 6,818
  • 11
  • 39
  • 70