ArtFranco
ArtFranco

Reputation: 360

MySQL JOIN using more than one column and table

I have 3 tables that I need to JOIN, but I'm having difficulty getting the right result because I need information from more than 1 column. I wish to get all users that are available and has the status = 1. In addition, get both types 1 and 3. With users listed as type 3, I need to join with the other table (by user id) to get only users with a specific specialty listed on the other table.

My tables are similar to these:

users
id | status | availability | type 
1  | 1      | 1            | 1
2  | 1      | 0            | 1
3  | 0      | 0            | 2
4  | 1      | 1            | 3
5  | 1      | 1            | 3


specialties
id | type 
1  | 1
2  | 2
3  | 3
4  | 43 

My relation table would look like this:

rel_users_specialties
id | id_user | id_specialty
1  | 1       | 29
2  | 2       | 3
3  | 4       | 3
4  | 5       | 3

My query would be:

SELECT *
FROM users u
JOIN rel_users_specialties r ON r.id_user = u.id
WHERE u.status = 1 
AND u.disponibilidade = 1
AND r.id_specialty = 3 
AND (u.type = 3 OR u.type = 1)

My expected result would be the following users (by id) 1, 4 and 5 (exclude user number 2 because of the availability = 0) and Although the user 1 has a specialty different than 3 it also has a type 1 (type one here would be a constant, regardless of the specialty selected). Appreciate the help!

Upvotes: 0

Views: 103

Answers (1)

forpas
forpas

Reputation: 164064

Set the conditions like this:

SELECT u.*
FROM users u INNER JOIN rel_users_specialties r 
ON r.id_user = u.id
WHERE u.status = 1 AND u.availability = 1 
  AND ((u.type = 1) OR (u.type = 3 AND r.id_specialty = 3))

Or without a join:

SELECT u.*
FROM users u 
WHERE u.status = 1 AND u.availability = 1 
  AND (
    (u.type = 1) 
    OR 
    (u.type = 3 AND EXISTS(SELECT 1 FROM rel_users_specialties r WHERE r.id_user = u.id AND r.id_specialty = 3))
  )

See the demo.

Upvotes: 2

Related Questions