Tuesday 4 September 2018

How to optimize the mysql query

How to increase the performance of this mysql query

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


Your example code has a correlated subquery. MySQL performs poorly with those, as of late 2016.
Try converting it to a JOINed table.
   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

I used LEFT JOIN. Without the LEFT, any rows without a matching entry in that table will be suppressed from the result set.

0 comments:

Post a Comment