简体   繁体   English

MySQL JOIN 使用多个列和表

[英]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.我有 3 个表需要加入,但我很难获得正确的结果,因为我需要来自 1 个以上列的信息。 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.我希望获取所有可用且状态为 1 的用户。此外,获取类型 1 和 3。将用户列为类型 3,我需要加入另一个表(按用户 ID)以仅获取用户具有另一张表中列出的特定专业。

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).我的预期结果将是以下用户(按 id)1、4 和 5(排除用户编号 2,因为可用性 = 0)并且虽然用户 1 的专业不同于 3,但它也有类型 1(类型 1 在这里将是一个常数,无论选择什么专业)。 Appreciate the help!感谢帮助!

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 .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM