首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用UNION ALL和LEFT联接时限制

使用UNION ALL和LEFT联接时限制
EN

Stack Overflow用户
提问于 2018-10-19 16:49:24
回答 2查看 158关注 0票数 2

显然,当使用UNION或UNION时,所有的性能都会受到影响。当我不使用UNION或UNION时,我的页面加载速度要快5-10倍。我想为查询添加一个限制,以帮助解决性能问题。

问题是当我添加限制5时,我只从第一次选择中得到5条记录。我需要为每个选择5条记录。所以我总共应该有15张唱片。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-10-19 16:51:27

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

若要对单个SELECT应用ORDER或ORDER,请将子句放在括住SELECT的括号内。

还有一点是有趣的:

但是,对单个SELECT语句使用ORDER语句并不意味着行在最终结果中出现的顺序,因为UNION默认情况下生成一组无序行。因此,在此上下文中使用ORDER通常与限制结合使用,因此它用于确定要为SELECT检索的选定行的子集,即使它不一定会影响最终UNION结果中这些行的顺序。如果在SELECT中无限制地出现ORDER,则会对其进行优化,因为它无论如何都不会产生任何效果。

更新的SQL Fiddle

代码语言:javascript
复制
(
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
EN

Stack Overflow用户

发布于 2018-10-19 16:59:11

您需要将LIMIT添加到每个SELECT状态,并在括号中包装所有查询。

代码语言:javascript
复制
(SELECT *
FROM table1
LIMIT 5)

UNION ALL
(SELECT *
FROM table2
LIMIT 5)

UNION ALL
(SELECT *
FROM table3
LIMIT 5)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52896769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档