MySQL Join with multiple conditions

后端 未结 4 1691
伪装坚强ぢ
伪装坚强ぢ 2020-12-23 11:34

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

相关标签:
4条回答
  • 2020-12-23 11:48

    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
    
    0 讨论(0)
  • 2020-12-23 11:56

    also this should work (not tested):

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

    If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

    Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

    0 讨论(0)
  • 2020-12-23 11:57
    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.

    0 讨论(0)
  • 2020-12-23 12:05

    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
    
    0 讨论(0)
提交回复
热议问题