Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having issues with a MySQL Join that needs to meet multiple conditions

Tags:

sql

join

mysql

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 Everything it's ok:

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  

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 it doesn't work:

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  

I don't understand why it doesn't work, but I can't figure up how to put the condition.

like image 211
Mihai Stancioiu Avatar asked Nov 05 '11 06:11

Mihai Stancioiu


People also ask

Can I join on multiple conditions SQL?

What are SQL multiple joins? Multiple joins can be described as follows; multiple join is a query that contains the same or different join types, which are used more than once. Thus, we gain the ability to combine multiple tables of data in order to overcome relational database issues.

How many join conditions are required to join 3 tables?

This formula can be extended to more than 3 tables to N tables, You just need to make sure that the SQL query should have N-1 join statement in order to join N tables. for joining two tables, we require 1 join statement and for joining 3 tables we need 2 join statements.

How do you join two tables based on conditions?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.


2 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 
like image 186
Andy Fleming Avatar answered Sep 23 '22 15:09

Andy Fleming


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.

like image 21
Ananth Avatar answered Sep 20 '22 15:09

Ananth