【发布时间】:2019-09-20 06:11:52
【问题描述】:
我有两个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 = user.id 的关系
我想要一个运行条件连接的查询。
如果user.type 是 'a' 或 's',则将从用户表中获取名称。
如果 user.type 是 'r' 且 ruser_type 是 'c',则名称将从带有 JOIN 条件 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 编写这个查询?
【问题讨论】:
-
一种懒惰的方法是
UNION2 个查询的结果。一份给管理员,一份给客户。 -
可以在那里找到另一个解决方案:stackoverflow.com/questions/4706100/…
-
与所有相关表的 SHOW CREATE TABLE 语句一样,关于查询优化的问题总是需要给定查询的 EXPLAIN。
标签: mysql laravel-5.7