I have two tables.
users
| id | name |
| ---|-------|
| 1 | Jhon |
| 2 | David |
swipes
| id | swp_from | swp_to| first_swp| second_swp |
| ---|----------|-------|----------|------------|
| 1 | 1 | 2 | like | pending |
| 2 | 1 | 2 | like | pending |
I need to join these to tables from both swp_from and swp_to depending upon condition.
My query goes like this:
SELECT name, swp_to, first_swp FROM swipes
LEFT JOIN users ON users.id = swipes.swp_to // JOINING WITH swp_to TO MATCH FIRST WHERE CONDITION
WHERE
(swipes.swp_from = :me AND ((swipes.first_swp NOT IN ('like', 'superlike')) OR (swipes.first_swp IN ('like', 'superlike') AND swipes.second_swp NOT IN ('like', 'superlike')))) // FIRST CONDITION
OR
(swipes.swp_to = :me AND swpipes.second_swp != 'pending') // FOR THIS SECOND CONDITION I NEED TO JOIN USERS TABLE USING swp_from AS WELL IN THIS SAME QUERY
As explained in the query above I have already joined swp_to with the users table. But I also need to join swp_from for the second condition in WHERE clause with the users table. How can I do that?
In simple terms, I need the query to join with users table using swp_to if the first where condition is satisfied. If the second where condtion (after OR) is satisfied then I want the join to work with swp_from instead of swp_to. This should happen for each row. A PHP conditional logic workaround can also be fine.
The conditions should be moved to the
ONclause.In MySql a
CASEexpression can be used to return the result of Boolean expressions (as1or0fortrueorfalse) like this: