简体   繁体   English

存储子查询的结果以用于多个联接

[英]Store the results of a sub-query for use in multiple joins

I have the following MySQL query, which produces the result I want: 我有以下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

But as you can see, it has the same sub-query in it three times. 但正如您所看到的,它在其中具有相同的子查询三次。 Is there any way to execute this query once and store the result, so I can LEFT JOIN with the cached results instead of executing the same query three times? 有没有办法执行此查询一次并存储结果,所以我可以使用缓存的结果LEFT JOIN而不是执行相同的查询三次?

I have tried storing it in a variable: 我已经尝试将其存储在变量中:

SET @usercache = (
  SELECT '0' AS 'id', 'Unassigned' AS 'name'
  UNION ALL
  SELECT `id`, `name`
  FROM `web_users`
)

...but this gives me an error: ......但这给了我一个错误:

1241 - Operand should contain 1 column(s) 1241 - 操作数应包含1列

...and some Googling on this error has left me none the wiser. ...而一些谷歌搜索这个错误让我没有更聪明。

Does anyone know how I can make this query more efficient? 有谁知道如何使这个查询更有效? Or am I just worrying about something that doesn't matter anyway? 或者我只是担心无关紧要的事情?

I am using PHP/MySQLi if it makes any difference. 如果它有任何区别,我正在使用PHP / MySQLi。

Do you really need the subqueries? 你真的需要子查询吗? How about this: 这个怎么样:

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.

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