我有两个 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/