[英]How would you optimize this MySQL query
Can anybody help me in optimizing this query, 任何人都可以帮我优化这个查询,
SELECT(X1,
X2
FROM TABLEAA
WHERE
Y IN (SELECT Y FROM TABLEBB WHERE Z=SELECTED)
AND Y IN (SELECT Y FROM TABLECC WHERE ZZ=SELECTED)
)
WHERE AS 在哪里
TABLEAA : 1 million enteries
TABLEBB : 22 million enteries
TABLECC : 1.2 million enteries
it works but take too much time, almost 30 sec 它有效,但需要花费太多时间,差不多30秒
Is there any other way to right this? 还有其他方法可以解决这个问题吗?
edit: the Z and ZZ are totally two different column 编辑:Z和ZZ完全是两个不同的列
Instead of using subqueries, join TABLEBB and TABLECC to TABLEAA, and check for ZZ=SLECTED in your WHERE clause, for both joined tables. 对于两个连接表,不是使用子查询,而是将TABLEBB和TABLECC连接到TABLEAA,并在WHERE子句中检查ZZ = SLECTED。
Make sure the columns that participate in the outer joins are indexed. 确保参与外部联接的列已编制索引。
I would use JOINs
: 我会使用JOINs
:
SELECT DISTINCT
A.X1,
A.X2
FROM TABLEAA A
JOIN TABLEBB B ON A.Y = B.Y AND B.Z='SELECTED'
JOIN TABLECC C ON A.Y = C.Y AND C.Z='SELECTED'
Also, make sure you have the appropriate indexes on AY, BY and CY You may find a better performance by adding indexes on you Z columns -- this depends on your table structure and several other factors. 另外,确保在AY,BY和CY上有适当的索引通过在Z列上添加索引可以找到更好的性能 - 这取决于您的表结构和其他几个因素。
Indexes... 索引...
Z
in TABLEBB
在TABLEBB
为Z
添加索引 ZZ
in TABLECC
在TABLECC
为ZZ
添加索引 Y
in TABLEAA
在TABLEAA
向Y
添加索引 SELECT X1, X2 FROM TABLEAA
JOIN TABLEBB ON Y = Y JOIN TABLECC ON Y = Y
WHERE TABLEBB.Z = SLECTED && TABLECC.ZZ = SLECTED
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.