mySQL - 如何解释我的 EXPLAIN 结果并优化此查询?

发布于 2024-12-09 05:36:04 字数 3558 浏览 6 评论 0原文

希望了解我的 EXPLAIN 结果在这里意味着什么,并尽可能优化此查询和我的表。

查询:

SELECT i.pending,
       i.itemid, 
       i.message,
       i.cid, 
       i.dateadded, 
       i.entrypoint,  
       SUM(CASE WHEN v.direction = 1 THEN 1
                     WHEN v.direction = 2 THEN -1
                     ELSE 0 END) AS votes,
       c.name AS cname,
       c.tag AS ctag,
       i.userid,
       (SELECT COUNT(commentid) FROM `comments` WHERE comments.itemid = i.itemid) AS commentcount,
       CASE WHEN NOT EXISTS (SELECT voteid FROM `votes` WHERE votes.itemid = i.itemid AND votes.userid = @userid) THEN '0' ELSE '1' END AS hasVoted,
       CASE WHEN NOT EXISTS (SELECT voteid FROM `user_favorites` WHERE user_favorites.itemid = i.itemid AND user_favorites.userid = @userid) THEN '0' ELSE '1' END AS isFavorite
    FROM `contentitems` i
      LEFT JOIN votes v ON i.itemid = v.itemid
      LEFT JOIN `user_favorites` uv ON i.itemid = uv.itemid AND (uv.userid = @userid)
      INNER JOIN  `categories` c ON i.cid = c.cid
    GROUP BY i.itemid
    HAVING SUM(CASE WHEN v.direction = 1 THEN 1
                    WHEN v.direction = 2 THEN -1
                    ELSE 0 END) > -3 AND i.pending = 0
    ORDER BY i.dateadded DESC

(编辑格式)

解释结果:

+----+--------------------+----------------+--------+-------------------------+-------------------------+---------+------------------------+------+-------------------------------------------------------
| id |    select_type     |     table      |  type  |      possible_keys                  key                               | key_len | ref                     | rows |              Extra              |
+----+--------------------+----------------+--------+-------------------------+-------------------------+---------+------------------------+------+------------------------------------------------------+
|  1 | PRIMARY            | i              | ALL    | NULL                              | NULL                              | NULL    | NULL                    |  121 | Using temporary; Using filesort |
|  1 | PRIMARY            | v              | ref    | fk_contentitemsitemid_votesitemid | fk_contentitemsitemid_votesitemid | 4       | db33481_mydb.i.itemid   |    2 |                                 |
|  1 | PRIMARY            | uv             | ALL    | NULL                              | NULL                              | NULL    | NULL                    |    7 |                                 |
|  1 | PRIMARY            | c              | eq_ref | PRIMARY                           | PRIMARY                           | 4       | db33481_mydb.i.cid      |    1 |                                 |
|  4 | DEPENDENT SUBQUERY | user_favorites | ALL    | NULL                              | NULL                              | NULL    | NULL                    |    7 | Using where                     |
|  3 | DEPENDENT SUBQUERY | votes          | ref    | fk_contentitemsitemid_votesitemid | fk_contentitemsitemid_votesitemid | 4       | func                    |    2 | Using where                     |
|  2 | DEPENDENT SUBQUERY | comments       | ALL    | NULL                              | NULL                              | NULL    | NULL                    |   26 | Using where                     |
+----+--------------------+----------------+--------+-------------------------+-------------------------+---------+------------------------+------+------------------------------------------------------+

Looking to understand what my EXPLAIN results mean here, and to optimize this query and my tables as best as I can.

The query:

SELECT i.pending,
       i.itemid, 
       i.message,
       i.cid, 
       i.dateadded, 
       i.entrypoint,  
       SUM(CASE WHEN v.direction = 1 THEN 1
                     WHEN v.direction = 2 THEN -1
                     ELSE 0 END) AS votes,
       c.name AS cname,
       c.tag AS ctag,
       i.userid,
       (SELECT COUNT(commentid) FROM `comments` WHERE comments.itemid = i.itemid) AS commentcount,
       CASE WHEN NOT EXISTS (SELECT voteid FROM `votes` WHERE votes.itemid = i.itemid AND votes.userid = @userid) THEN '0' ELSE '1' END AS hasVoted,
       CASE WHEN NOT EXISTS (SELECT voteid FROM `user_favorites` WHERE user_favorites.itemid = i.itemid AND user_favorites.userid = @userid) THEN '0' ELSE '1' END AS isFavorite
    FROM `contentitems` i
      LEFT JOIN votes v ON i.itemid = v.itemid
      LEFT JOIN `user_favorites` uv ON i.itemid = uv.itemid AND (uv.userid = @userid)
      INNER JOIN  `categories` c ON i.cid = c.cid
    GROUP BY i.itemid
    HAVING SUM(CASE WHEN v.direction = 1 THEN 1
                    WHEN v.direction = 2 THEN -1
                    ELSE 0 END) > -3 AND i.pending = 0
    ORDER BY i.dateadded DESC

(Edited Formatting)

The explain results:

+----+--------------------+----------------+--------+-------------------------+-------------------------+---------+------------------------+------+-------------------------------------------------------
| id |    select_type     |     table      |  type  |      possible_keys                  key                               | key_len | ref                     | rows |              Extra              |
+----+--------------------+----------------+--------+-------------------------+-------------------------+---------+------------------------+------+------------------------------------------------------+
|  1 | PRIMARY            | i              | ALL    | NULL                              | NULL                              | NULL    | NULL                    |  121 | Using temporary; Using filesort |
|  1 | PRIMARY            | v              | ref    | fk_contentitemsitemid_votesitemid | fk_contentitemsitemid_votesitemid | 4       | db33481_mydb.i.itemid   |    2 |                                 |
|  1 | PRIMARY            | uv             | ALL    | NULL                              | NULL                              | NULL    | NULL                    |    7 |                                 |
|  1 | PRIMARY            | c              | eq_ref | PRIMARY                           | PRIMARY                           | 4       | db33481_mydb.i.cid      |    1 |                                 |
|  4 | DEPENDENT SUBQUERY | user_favorites | ALL    | NULL                              | NULL                              | NULL    | NULL                    |    7 | Using where                     |
|  3 | DEPENDENT SUBQUERY | votes          | ref    | fk_contentitemsitemid_votesitemid | fk_contentitemsitemid_votesitemid | 4       | func                    |    2 | Using where                     |
|  2 | DEPENDENT SUBQUERY | comments       | ALL    | NULL                              | NULL                              | NULL    | NULL                    |   26 | Using where                     |
+----+--------------------+----------------+--------+-------------------------+-------------------------+---------+------------------------+------+------------------------------------------------------+

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

酒与心事 2024-12-16 05:36:04

首先,您有一个选择不存在的投票ID,然后在from中进行左连接,最后在having中进行求和。这已经是您投票表上的 3 次了。如果每个投票可能与单个“ItemID”相关联,那么最好将其本身预先聚合为一次完成的“总和”。

此外,由于最终的“HAVING”子句是投票的直接基础,因此对投票进行左连接会成为一个死点,并最终以正常的 JOIN 结束。

话虽这么说,我会首先预先查询以符合条件的 HAVING 条件完成的投票,然后加入到内容项和其他联接...针对 User_Favorites 的查询是一个计数,并且要么为 0(不是找到),或 1(找到)。应该不需要case/when

我的第一个查询别名“PQ”代表“PreQuery”

SELECT
      PQ.ItemID,
      PQ.VSum as Votes,
      PQ.HasVoted,
      i.pending,
      i.itemid, 
      i.message,
      i.cid, 
      i.dateadded, 
      i.entrypoint,  
      i.userid,
      c.name AS cname,
      c.tag AS ctag,
      ( SELECT COUNT(commentid) 
           FROM `comments` 
           WHERE comments.itemid = PQ.itemid) AS commentcount,
      ( SELECT COUNT(*) FROM user_favorites uf
              WHERE uf.itemid = PQ.itemid 
                AND uf.userid = @userid ) AS isFavorite
   from 
      ( SELECT
              v.itemid,
              SUM( case when v.Direction = 1 then 1
                        when v.Direction = 2 then -1
                        ELSE 0 end ) as VSum,
              MAX( if( votes.userid = @userid, 1, 0 ) AS HasVoted 
           from 
              votes v
           group by 
              v.itemid
           having
              VSum > -3 ) PQ

         JOIN ContentItems i
            ON PQ.ItemID = i.ItemID
            and i.Pending = 0

         JOIN Categories c
            ON i.cid = c.cid

   ORDER BY 
      i.dateadded DESC

其他人已经表明需要索引,同意。我将确保每个表在用户 ID 或项目 ID(或在适当的情况下两者)都有各自的索引。

结合其他点...您最初开始查询所有 ContentItems,但左连接投票...但然后应用用户 ID 的元素。这绝对有针对特定用户的查询的味道。话虽这么说,我会另外预先启动整个查询,仅选择用户 ID 已执行过任何操作的 ItemID...然后继续查询。

First, you have a select not exists vote ID, then do a left-join in the from, and finally a sum in the having. This is hitting your votes table 3 times. IF each vote is possibly associated to a single "ItemID", then that would be best to be pre-aggregated by itself as its own "Sum" done ONCE.

Additionally, since your final "HAVING" clause is a direct basis of the Votes, having a left join on votes becomes a dead point and ultimately ends in a normal JOIN.

All that being said, I would pre-query FIRST on the votes that FINISH with the qualifying HAVING condition up front, then join to the content items and other joins... The query against User_Favorites is a count and will either be 0 (not found), or 1 (found). There should be no need for a case/when

My first query alias "PQ" represents the "PreQuery"

SELECT
      PQ.ItemID,
      PQ.VSum as Votes,
      PQ.HasVoted,
      i.pending,
      i.itemid, 
      i.message,
      i.cid, 
      i.dateadded, 
      i.entrypoint,  
      i.userid,
      c.name AS cname,
      c.tag AS ctag,
      ( SELECT COUNT(commentid) 
           FROM `comments` 
           WHERE comments.itemid = PQ.itemid) AS commentcount,
      ( SELECT COUNT(*) FROM user_favorites uf
              WHERE uf.itemid = PQ.itemid 
                AND uf.userid = @userid ) AS isFavorite
   from 
      ( SELECT
              v.itemid,
              SUM( case when v.Direction = 1 then 1
                        when v.Direction = 2 then -1
                        ELSE 0 end ) as VSum,
              MAX( if( votes.userid = @userid, 1, 0 ) AS HasVoted 
           from 
              votes v
           group by 
              v.itemid
           having
              VSum > -3 ) PQ

         JOIN ContentItems i
            ON PQ.ItemID = i.ItemID
            and i.Pending = 0

         JOIN Categories c
            ON i.cid = c.cid

   ORDER BY 
      i.dateadded DESC

Others have indicated the need for indexes, agreed. I would ensure each table has respective index on either the user ID or Item ID (or both where appropriate).

Couple other points... You originally start query querying all ContentItems, but left-joining to votes... But then applying the element of a user ID. This DEFINITELY smells of a query for a specific user. That being said, I would ADDITIONALLY pre-start the entire query with a select of only ItemIDs the user ID has done anything with... THEN continue the query.

初相遇 2024-12-16 05:36:04

我发现没有用于访问 commentsvotesuser_favorites 的密钥。除非表非常小,否则您应该尝试在这些表中的 useriditemid 上添加索引。

I see that there is no key used to access comments, votes, and user_favorites. Unless the tables are really small you should try adding an index on userid and itemid in those tables.

春花秋月 2024-12-16 05:36:04

尝试查看此链接 用于理解解释计划。尝试查看该部分,它清楚地解释了您需要寻找的内容。

更多关于你的解释计划看起来信息较少。请尝试使用sql Developer< /strong> 来自甲骨文。它是开源的,并且确实为您提供了有关解释计划的适当详细信息。

Try seeing this link for understanding explain plan. Try going down that section, it clearly explains what you need to look for.

More over your explain plan looks like having less info. please try using sql developer from oracle. it is open source and does give you apt details about the explain plan.

所谓喜欢 2024-12-16 05:36:04

我将添加以下索引:

ALTER TABLE comments ADD INDEX (commentid)
ALTER TABLE user_favorites ADD INDEX (itemid, voteid)

此外,如果 possible_keys 列显示 NULL,则意味着该表没有可用的键。即使它们不用于优化,如果查询中的列存在它们,它们也会显示在那里。最有可能的是,这些表的主键位于查询中未访问的列上。

I would add the following indexes:

ALTER TABLE comments ADD INDEX (commentid)
ALTER TABLE user_favorites ADD INDEX (itemid, voteid)

In addition, if the possible_keys column says NULL, it means that there are no usable keys for that table. Even if they aren't used for the optimization, they will show up there if they exist for a column in the query. Most likely, you have a primary key on those tables on a column that is not being accessed in the query.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文