lundi 13 juin 2016

SQL - IF/ELSE Logic depending on table column

So, as you may have guessed, I am writing a query to select data from a database. And, as you may have also guessed, I am writing it with the logic of an If/Else statement. Obviously, this isn't as simple in SQL as we all wish it to be. To put the logic into simple terms, here's some sort of pseudo-code version:

SELECT * FROM table1 INNER JOIN table2 on col2 = col1
// Some other JOINS and irrelevant data stuff
if (table2.conditionalColumn == 'x') {
    JOIN table3 ON col3 = col2 WHERE a = 1, b = 2, c = 3
} else {
    JOIN table3 ON col3 = col2 JOIN table4 ON col4 = col3
}

I understand that the above query has no resemblance to a proper SQL query in the slightest. What I am trying to find out is how to work around having a column which has a value which determines whether to JOIN to one table, or to join to another table. The whole concept of this is similar to the friend-of-friend system for social networks.

Please feel free to ask for any further explanation of the issue if need be. I have attempted using some ORlogic, but I got completely stuck. How can I solve this issue?

Thanks!

Edit - To make it easier to understand my goal, I have added a scenario below:

I want to select data from a table named projects if the user has a row inside of the projects_members table, OR they have a row in the the teams table, and that team has a row inside of projects_members. There is a column inside of projects_members named memberType, which is set to 'user' or 'team'.

Aucun commentaire:

Enregistrer un commentaire