Home » Mysql » MySQL Join with multiple conditions

MySQL Join with multiple conditions

Posted by: admin November 1, 2017 Leave a comment

Questions:

I have a problem with an sql query, actually a simple query but I can’t figure up what am I missing, so I came to ask your help…
So, what i have to do

I have two tables rooms and rooms facilities…and I have to select the rooms with desired facilities..

If I select a room with one facility (facility with id=4 – id_fu – )…using the following query

SELECT u.* FROM rooms u 
JOIN facilities_r fu 
ON fu.id_uc = u.id_uc 
    AND fu.id_fu = '4' 
WHERE 1 
    AND vizibility='1' 
GROUP BY id_uc 
ORDER BY u_premium desc, id_uc DESC 

everything it’s ok.

But if I want to select the room with more facilities, let’s say facilities with id=4, and id=3 ..using the following query

SELECT u.* FROM room u 
JOIN facilities_r fu 
ON fu.id_uc=u.id_uc 
    AND fu.id_fu = '4' 
    AND fu.id_fu = '3' 
WHERE 1 
    AND vizibility = '1' 
GROUP BY id_uc 
ORDER BY u_premium DESC, id_uc DESC 

it doesn’t work.

I can’t understand why it doesn’t work, but I can’t figure up how to put the condition…

Thanks, Mihai

Answers:

You can group conditions with parentheses. When you are checking if a field is equal to another, you want to use OR. For example WHERE a='1' AND (b='123' OR b='234').

SELECT u.*
FROM rooms AS u
JOIN facilities_r AS fu
ON fu.id_uc = u.id_uc AND (fu.id_fu='4' OR fu.id_fu='3')
WHERE vizibility='1'
GROUP BY id_uc
ORDER BY u_premium desc, id_uc desc

Questions:
Answers:
SELECT 
    u . *
FROM
    room u
        JOIN
    facilities_r fu ON fu.id_uc = u.id_uc
        AND (fu.id_fu = '4' OR fu.id_fu = '3')
WHERE
    1 and vizibility = '1'
GROUP BY id_uc
ORDER BY u_premium desc , id_uc desc

You must use OR here, not AND.

Since id_fu cannot be equal to 4 and 3, both at once.

Questions:
Answers:

If you join the facilities table twice you will get what you are after:

select u.* 
from room u 
  JOIN facilities_r fu1 on fu1.id_uc = u.id_uc and fu1.id_fu = '4'
  JOIN facilities_r fu2 on fu2.id_uc = u.id_uc and fu2.id_fu = '3' 
where 1 and vizibility='1' 
group by id_uc 
order by u_premium desc, id_uc desc