简体   繁体   English

使用 `COUNT` 优化 SQL 查询

[英]Optimize SQL query using `COUNT`

I have the SQL query (I am using MariaDB/MySQL) below which works fine.我有下面的 SQL 查询(我正在使用 MariaDB/MySQL),它工作正常。 But I am wondering if I can simplify/optimize it.但我想知道我是否可以简化/优化它。 The difficulty I am facing is because of COUNT with INNER JOIN .我面临的困难是因为COUNT with INNER JOIN Do I really need the subquery IN or you think there is a way I can eliminate it?我真的需要子查询IN还是您认为有办法可以消除它?

SELECT a.* 
FROM aaa a 
INNER JOIN bbb b ON a.field1 = b.field1 
WHERE a.yyy = 'yyy' AND b.zzz = 'zzz' 
AND a.field1 IN (
    SELECT field1 
    FROM bbb 
    WHERE xxx = 'x' 
    GROUP BY field1 
    HAVING COUNT(field1) <= 5
)

Thank you!谢谢!

Your query may be as good as possible, but you can also try joining with the subquery instead of using IN .您的查询可能尽可能好,但您也可以尝试加入子查询而不是使用IN

SELECT DISTINCT a.*
FROM aaa AS a
INNER JOIN bbb b ON a.field1 = b.field1 
INNER JOIN (
    SELECT field1 
    FROM bbb 
    WHERE xxx = 'x' 
    GROUP BY field1 
    HAVING COUNT(*) <= 5
) AS bc ON a.field1 = bc.field1
WHERE a.yyy = 'yyy' AND b.zzz = 'zzz' 

I like Barmar's answer, but because of the filtering on b , I suggest a small(?) change.我喜欢 Barmar 的回答,但由于对b的过滤,我建议进行小的(?)更改。 (I rearrange the tables primarily to follow the Optimizer's likely order.) (我重新排列表格主要是为了遵循优化器的可能顺序。)

SELECT DISTINCT a.*
FROM  (
    SELECT field1 
    FROM bbb 
    WHERE xxx = 'x' 
    GROUP BY field1 
    HAVING COUNT(*) <= 5
) AS bc
INNER JOIN bbb AS b ON b.field1 = bc.field1 
INNER JOIN aaa AS a ON a.field1 = bc.field1
WHERE b.zzz = 'zzz' 
  AND a.yyy = 'yyy'

Plus these indexes:加上这些索引:

    bbb:  INDEX(xxx, field1)  -- this order
    b:    INDEX(field1, zzz)  -- either order
    a:    INDEX(field1, yyy)  -- either order

The first two composite indexes will be "covering".前两个复合索引将是“覆盖”。

The main change from Barmar's answer was to leave a.* for last. Barmar 回答的主要变化是将a.*留在最后。

If you want to discuss this Question further, it may be useful to provide SHOW CREATE TABLE and EXPLAIN .如果您想进一步讨论这个问题,提供SHOW CREATE TABLEEXPLAIN可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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