elunap
elunap

Reputation: 841

SQL Server: Query Right Join

I have 3 tables:

Users:

Oid | email | pass

Dist:

Oid | Name | Users

CS:

Oid | Name | Users | Dist

I want to bring all Of the users and also the name of the CS and the name of the Dist, if is the case.

This is what I tried:

SELECT 
    Users.*, CS.OID as OidCS, CS.Name as NameCs,
    Dist.OID as OidDist, Dist.Name as NameDist
FROM
    Dist, Users
RIGHT JOIN 
    CS on CS.Users = Users.OID
WHERE 
    CS.Dist = Dist.OID

But this query doesn't bring me the Dist Users and I need them both (Cs and Dist), I don't know how to approach for the solution, How can I solve it?

Thanks.

Upvotes: 0

Views: 47

Answers (2)

Siyual
Siyual

Reputation: 16917

You're mixing an ancient implicit JOIN syntax (that has been deprecated for over 25 years) with an explicit one. This is going to cause some issues with your results.

As a rule-of-thumb, you should never have a , in the FROM clause. You should always use explicit the JOIN syntax.

In this case, using a LEFT JOIN makes more logical sense. You're wanting to select everything from Users and select records from Dist and CS if they exist.

This should get you what you need:

Select      U.*, C.OID As OIDCS, C.Name As NameCs,
            D.OID As OIDDist, D.Name As NameDist
From        Users   U
Left Join   CS      C   On  U.OID = C.Users
Left Join   Dist    D   On  D.OID = C.Dist

Upvotes: 2

M Amir Shahzad
M Amir Shahzad

Reputation: 318

may be there is a problem in your sql syntax you are using table names as for matches like this.

WHERE CS.Dist=Dist.OID.

CS is a table and Dist is also a table you are using assignment operator here you have to update the logic here compare columns of table not two tables.

got it?

Upvotes: -1

Related Questions