I am trying to learn about MYSQL Joins but am having trouble figuring this one out. I want to get all rows in table1 where the userID is in a relationship with the given user.
table2 contains user relationships so the userID can either be in iduser1 field or iduser2 field
I have the following query that gives me the correct results:
set @userID = 91;
SELECT * FROM table1
WHERE (iduser IN (SELECT iduser1 FROM table2 WHERE iduser2 = @userID)
OR (iduser IN (SELECT iduser2 FROM table2 WHERE iduser1 = @userID)))
table1:
iduser FK
table2:
iduser1 FK
iduser2 FK
I have been told that nested queries in MySQL have a bad reputation when it comes to performance and I am sure I could probably do this same query using JOINS somehow but I just cant figure it out especially as there is an OR statement because the table1.iduser can be in either table2.iduser1 OR table2.iduser2
How can I join the same table twice?
Given this expression:
Using EXISTS, you can reduce that two subqueries into following:
The OR might slowdown your query, it doesn’t necessarily short-circuit in RDBMS. In that case, you should try to short-circuit it by using CASE WHEN. I had a query that took 5 seconds to execute when using OR, but took sub-zero second when I translated it to CASE WHEN:
Boolean expression automatically cast to integer(either 0(false) or 1(true)), so you can also do it like this:
Or this:
If you are not using MySQL, you shall do it like this: