0

I am looking to dynamically select specific columns within a join query in which a specific field will only be selected if the value of another is not equal to 0.

So here's what I have going on.

The query uses the following 3 tables, users - schools - campuses

I would like to select all of the data from users, and if the campus_id field of users is not equal to 0, then I would like to include the campus name field of campuses where campuses.id = users.campus_id, how would I do this?

3

2 Answers 2

2

You could use CASE WHEN

SELECT column1, column2, (CASE WHEN U.campus_id<>0 THEN campus_name) FROM USERS U, CAMPUSES C
WHERE (U.campus_id <>0 AND C.id=U.campus_id)
Sign up to request clarification or add additional context in comments.

2 Comments

How would I do this if I want more than 1 where condition?
@BraydonBatungbacal the you could use CASE WHEN .... THEN ... WHEN ... THEN .... ELSE check the documentation
0
select * from users u  
left join campuses c on (u.campus_id = c.id)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.