• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Can SQL do conditional join?

Semidevil

Diamond Member
I have a ''student" table I want to join with an "ID" table.

The "ID" table has 3 columns: "code" (I.e xxx), "sub code" (xxx-yy), and "type" (I.e, "aaa" or "bbb").

My issue is I want to left join by "xxx" when type = "aaa" and join by "xxx-yy" when type = "bbb".

How do I join with this condition?

I tried

select *

From students s
Left join ID as IDnum on s.code = IDnum.code and idnum = 'aaa'
Left join ID as IDnum on s.subcode = IDnum.code and idnum = ''bbb'

This gives me an error for using the table twice in my join
 
Last edited:
Doing a join is just like doing a WHERE statement which means you can include functions, ORs ,ANDs etc.

Code:
From students s
Left join ID as IDnum on (s.code = IDnum.code and idnum = 'aaa') OR (s.subcode = IDnum.code and idnum = ''bbb')
 
Thanks. That makes sense. Now, when I do a group by, it gives me an 'invalid column name," and it is pointing to all my group by lines.

(I realize I need the aggregate functions. These are all in my code)
 
I have a ''student" table I want to join with an "ID" table.

The "ID" table has 3 columns: "code" (I.e xxx), "sub code" (xxx-yy), and "type" (I.e, "aaa" or "bbb").

My issue is I want to left join by "xxx" when type = "aaa" and join by "xxx-yy" when type = "bbb".

How do I join with this condition?

I tried

select *

From students s
Left join ID as IDnum on s.code = IDnum.code and idnum = 'aaa'
Left join ID as IDnum on s.subcode = IDnum.code and idnum = ''bbb'

This gives me an error for using the table twice in my join

In addition to what was mentioned previously, if you alias the second reference to the table differently, that would work too.

select *
From students s
Left join ID as IDnum on s.code = IDnum.code and idnum = 'aaa'
Left join ID as IDnum2 on s.subcode = IDnum2.code and idnum = ''bbb'
 
Back
Top