[英]Store the results of a sub-query for use in multiple joins
我有以下MySQL查询,它产生我想要的结果:
SELECT
`l`.`status`,
`l`.`acquired_by`, `a`.`name` AS 'acquired_by_name',
`l`.`researcher`, `r`.`name` AS 'researcher_name',
`l`.`surveyor`, `s`.`name` AS 'surveyor_name'
FROM `leads` `l`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `r` ON `r`.`id` = `l`.`researcher`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `s` ON `s`.`id` = `l`.`surveyor`
LEFT JOIN (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
) `a` ON `a`.`id` = `l`.`acquired_by`
WHERE `l`.`id` = 566
但正如您所看到的,它在其中具有相同的子查询三次。 有没有办法执行此查询一次并存储结果,所以我可以使用缓存的结果LEFT JOIN
而不是执行相同的查询三次?
我已经尝试将其存储在变量中:
SET @usercache = (
SELECT '0' AS 'id', 'Unassigned' AS 'name'
UNION ALL
SELECT `id`, `name`
FROM `web_users`
)
......但这给了我一个错误:
1241 - 操作数应包含1列
...而一些谷歌搜索这个错误让我没有更聪明。
有谁知道如何使这个查询更有效? 或者我只是担心无关紧要的事情?
如果它有任何区别,我正在使用PHP / MySQLi。
你真的需要子查询吗? 这个怎么样:
SELECT
`l`.`status`,
`l`.`acquired_by`, COALESCE(`a`.`name`, 'Unassigned') AS 'acquired_by_name',
`l`.`researcher`, COALESCE(`r`.`name`, 'Unassigned') AS 'researcher_name',
`l`.`surveyor`, COALESCE(`s`.`name`, 'Unassigned') AS 'surveyor_name'
FROM `leads` `l`
LEFT JOIN `web_users` `r` ON `r`.`id` = `l`.`researcher`
LEFT JOIN `web_users` `s` ON `s`.`id` = `l`.`surveyor`
LEFT JOIN `web_users` `a` ON `a`.`id` = `l`.`acquired_by`
WHERE `l`.`id` = 566
你不能运行一次 - 你实际上使用它三次得到三个不同的结果......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.