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

时间:2012-03-06 13:06:04

标签: mysql caching

我有以下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。

2 个答案:

答案 0 :(得分:2)

你真的需要子查询吗?怎么样:

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

答案 1 :(得分:0)

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