简体   繁体   中英

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

I have the following MySQL query, which produces the result I want:

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?

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)

...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.

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

你不能运行一次 - 你实际上使用它三次得到三个不同的结果......

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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