如何优化mysql查询

时间:2016-12-10 13:15:13

标签: mysql sql performance

如何提高这个mysql查询的性能

SELECT ''                                           AS sharedid,
       hubber_posts.userID                          AS postowner,
       hubber_posts.*,
       ''                                           AS sharedby,
       hubber_posts.userID                          AS userID,
       hubber_posts.posted_date                     AS DATE,
       ''                                           AS sharebyusr,
       ''                                           AS sharebyusrimg,
       Concat_ws(' ', firstname, lastname)          AS fullname,
       username                                     AS postedBy,
       hubber_user.image,
       hubber_user.gender                           AS gender,
       (SELECT accounttype
        FROM   hubber_user_security us
        WHERE  hubber_user.ID = us.userID
               AND hubber_posts.userID = us.userID) AS accounttype,
       ''                                           AS sharebyusrtype
FROM   hubber_posts
       INNER JOIN hubber_user
               ON hubber_posts.userID = hubber_user.ID
WHERE  hubber_posts.status = 1 

3 个答案:

答案 0 :(得分:0)

我的建议是支持一个连接,其中hubber_posts是基表,另外两个表是使用嵌套循环连接的。

  • 无需为加入索引hubber_posts。
  • hubber_user.ID应为PK。
  • 应将hubber_user_security.userID编入索引(并定义为FK引用hubber_user.ID)。

对于WHERE子句 - 只有当hubber_posts.status = 1的行数相对较少时,才应在hubber_posts.status上添加索引

P.S。

因为连接包含条件 -

ON hubber_posts.userID = hubber_user.ID 

无需将hubber_posts.userIDhubber_user.IDus.userID进行比较

答案 1 :(得分:0)

您的示例代码具有相关的子查询。截至2016年底,MySQL的表现不佳。

尝试将其转换为JOINed表。

   SELECT all that stuff,
          us.accounttype
     FROM   hubber_posts
     JOIN hubber_user ON hubber_posts.userID = hubber_user.ID
     LEFT JOIN hubber_user_security us ON hubber_user.ID = us.userID
    WHERE  hubber_posts.status = 1 

我使用了LEFT JOIN。如果没有LEFT,那么该表中没有匹配条目的任何行都将从结果集中被禁止。

答案 2 :(得分:0)

您的查询基本上是这样的:

SELECT . . .
       (SELECT accounttype
        FROM   hubber_user_security us
        WHERE  u.ID = us.userID AND
               p.userID = us.userID
       ) AS accounttype,
       . . .
FROM hubber_posts p INNER JOIN
     hubber_user u
     ON p.userID = u.ID
WHERE p.status = 1 ;

对于此查询,最佳索引为:

  • hubber_posts(status, userId)
  • hubber_user(Id)
  • hubber_user_security(userId)

我会注意到子查询有一个额外的相关条件,这是不必要的 - 用户ID已经相等。而且,如果有多种帐户类型,则存在收到错误的风险。

您可能打算:

   (SELECT GROUP_CONCAT(accounttype)
    FROM   hubber_user_security us
    WHERE  u.ID = us.userID
   ) as accounttypes,
相关问题