使用UNION ALL和LEFT JOIN时的限制

时间:2018-10-19 16:49:24

标签: php mysql

显然,在使用UNION或UNION ALL时,性能会受到影响。当我不使用UNION或UNION ALL时,页面加载速度提高了5-10倍。我想在查询中添加一个LIMIT来解决性能问题。

问题是当我添加LIMIT 5时,我从第一个SELECT中仅获得5条记录。每个SELECT我需要5条记录。因此,我总共应该有15条记录。

下面是一个示例:http://sqlfiddle.com/#!9/3617ee/6

2 个答案:

答案 0 :(得分:1)

要对UNION中的单个选择查询使用限制,请将其括在括号中。来自Union文档:

  

要将ORDER BY或LIMIT应用于单个SELECT,请放置子句   在包围SELECT的括号内

另一个有趣的地方:

  

但是,对单个SELECT语句使用ORDER BY意味着   行在最终结果中出现的顺序无关紧要   因为默认情况下UNION会生成无序的行集。因此,   在这种情况下,通常将ORDER BY与   LIMIT,以便用于确定所选行的子集   检索SELECT,即使它不一定会影响   这些行在最终UNION结果中的顺序。 如果出现ORDER BY   在SELECT中没有LIMIT的情况下,它已被优化,因为它将具有   仍然没有效果。

Updated SQL Fiddle

(
SELECT 

openservicecalls.serial,
openservicecalls.company,

product1_errors.serial,
product1_errors.error,

description.error,
description.description,

masterlist.serial,
masterlist.phonenumber

FROM product1_errors
LEFT JOIN description
ON product1_errors.error = description.error
LEFT JOIN openservicecalls
ON product1_errors.serial = openservicecalls.serial
LEFT JOIN masterlist
ON product1_errors.serial = masterlist.serial LIMIT 5
)

UNION ALL

(
SELECT 

openservicecalls.serial,
openservicecalls.company,

product2_errors.serial,
product2_errors.error,

description.error,
description.description,

masterlist.serial,
masterlist.phonenumber

FROM product2_errors
LEFT JOIN description
ON product2_errors.error = description.error
LEFT JOIN openservicecalls
ON product2_errors.serial = openservicecalls.serial
LEFT JOIN masterlist
ON product2_errors.serial = masterlist.serial LIMIT 5
)

UNION ALL

(
 SELECT 

openservicecalls.serial,
openservicecalls.company,

product3_errors.serial,
product3_errors.error,

description.error,
description.description,

masterlist.serial,
masterlist.phonenumber

FROM product3_errors
LEFT JOIN description
ON product3_errors.error = description.error
LEFT JOIN openservicecalls
ON product3_errors.serial = openservicecalls.serial
LEFT JOIN masterlist
ON product3_errors.serial = masterlist.serial  LIMIT 5
)

答案 1 :(得分:1)

您需要在每个LIMIT语句中添加SELECT,并将所有查询括在括号中

(SELECT *
FROM table1
LIMIT 5)

UNION ALL
(SELECT *
FROM table2
LIMIT 5)

UNION ALL
(SELECT *
FROM table3
LIMIT 5)
相关问题