mysql - MySQL 中的条件 JOIN 查询

标签 mysql laravel-5.7

我有两个 mysql 表

用户:

|--------------------------------|
| id | name  | type | ruser_type |
|--------------------------------|
|  1 | Admin | a    |            |
|  2 |       | r    |      c     |
|--------------------------------|

客户

|-------------------------|
|  id  |  name  | user_id | 
|-------------------------|
|  1   |  Sam   |    2    |
|-------------------------|

如果user.type是“a”或“s”,则其名称在用户表中的管理员用户。

如果 user.type 为“r”且 ruser_type 为“c”,则其常规用户在客户表中具有关系,其中 customer.user_id = 用户.id

我想要一个运行条件连接的查询。 如果 user.type 是“a”或“s”,则将从用户表中获取名称。

如果 user.type 为“r”且 ruser_type 为“c”,则将从具有 JOIN 条件 customer.customer 的客户表中获取名称。 user_id = user.id.

为此,我编写了一个如下查询:-

SELECT users.fname as adminFname, customers.fname as customerFname, users.type FROM users
LEFT JOIN customers ON (customers.user_id = users.id AND 
                            ( 
                                (users.type = 'r' AND users.ruser_type = 'c') 
                                    OR users.type = 'a' 
                                    OR users.type = 's'
                            )
                       )
                        WHERE users.id = 1

是否有可能进一步优化查询?

另外,如何使用 Laravel eloquent 编写此查询?

最佳答案

FWIW,我发现这更容易阅读......

SELECT u.fname adminFname
     , c.fname customerFname
     , u.type 
  FROM users u
  LEFT 
  JOIN customers c
    ON c.user_id = u.id 
 WHERE u.id = 1
   AND (
        (u.type = 'r' AND u.ruser_type = 'c')
     OR (u.type IN('a','s'))
       )

关于mysql - MySQL 中的条件 JOIN 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58022677/

相关文章:

Laravel 5.7 - 未发送验证电子邮件

Laravel 5.7 使用 Expo 发送通知

mysql - 使用 Laravel > 5.6 在 json 列中选择非空值的正确方法?

mysql - 从其他表中加入最大值的最佳和最佳方式

mysql - 按年循环多个数组

mysql - 如何检测 MySQL 索引是否必要或必需?

MySQL 按 3 列分组

javascript - 事件不会出现在 php 日历上

php - 如何使用 Eloquent ORM 创建三向枢轴