[英]how to optimize the mysql Query
如何提高这个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
我的建议是支持一个join,其中hubber_posts是基表,另外两个表是使用嵌套循环连接的。
至于WHERE子句 - 只有当hubber_posts.status = 1的行数相对较少时,才应在hubber_posts.status上添加索引
PS
由于连接包含条件 -
ON hubber_posts.userID = hubber_user.ID
无需将hubber_posts.userID
和hubber_user.ID
与hubber_user.ID
进行us.userID
您的示例代码具有相关子查询。 截至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
,则将从结果集中抑制该表中没有匹配条目的任何行。
您的查询基本上是这样的:
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,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.