这是执行MySQL查询的最佳/有效方式

时间:2016-02-24 07:02:38

标签: mysql join optimization query-optimization mysql-workbench

第一种方法: -

SELECT 
    clipComment.commentId,
    clipComment.commentedBy,
    clipComment.clipId AS commentTypeId,
    'clip' AS commentType,
    clipComment.commentDescription,
    clipComment.commentCreatedDateTime,
    clipComment.commentModifiedDateTime,
    clipComment.commentLikeCount,
    userProfile.userName,
    userProfile.firstName,
    userProfile.LastName,
    userProfile.profilePicUrl,
    userProfile.themeForeground,
    userProfile.themeBackground,
    IF(derCommentLike.commentId = clipComment.commentId,
        1,
        0) likedByMe
FROM
    clipComment
LEFT JOIN
    (SELECT 
        *
    FROM
        clipCommentLikes
    WHERE
        commentLikedBy = 16) derCommentLike 
ON 
    derCommentLike.commentId = clipComment.commentId
LEFT JOIN
    userProfile 
ON 
    userProfile.userId = clipComment.commentedBy
WHERE
    clipComment.clipId = 141

第二种方法: -

SELECT
    clipComment.commentId,
    clipComment.commentedBy,
    clipComment.clipId AS commentTypeId,
    'clip' AS commentType,
    clipComment.commentDescription,
    clipComment.commentCreatedDateTime,
    clipComment.commentModifiedDateTime,
    clipComment.commentLikeCount,
    userProfile.userName,
    userProfile.firstName,
    userProfile.LastName,
    userProfile.profilePicUrl,
    userProfile.themeForeground,
    userProfile.themeBackground,
    IF( derCommentLike.commentId = clipComment.commentId , 1 , 0 ) AS likedByMe
FROM
    (SELECT
        *
     FROM
        clipCommentLikes
     WHERE
        commentLikedBy = 16) derCommentLike
    RIGHT OUTER JOIN clipComment
     ON derCommentLike.commentId = clipComment.commentId
    RIGHT OUTER JOIN userProfile
     ON clipComment.commentedBy = userProfile.userId
WHERE
    clipComment.clipId = 141

两个查询返回相同的结果,但只是想知道我应该遵循哪种方法&哪一个更有效率。记录集将包含数百万条记录,所以我想用最好的方法。或者我正在做工作然后请纠正我。先感谢您。

解释声明第一种方法 1st approach

解释声明第二种方法 2nd approach

解释声明第一种方法

1 个答案:

答案 0 :(得分:0)

    IF(derCommentLike.commentId = clipComment.commentId, 1, 0) likedByMe
...
LEFT JOIN
    (SELECT  *
        FROM clipCommentLikes
        WHERE commentLikedBy = 16
    ) derCommentLike 
   ON    derCommentLike.commentId = clipComment.commentId

- >

   ( EXISTS SELECT * FROM clipCommentLikes
         WHERE commentId = clipComment.commentId
   ) AS  likedByMe

说明:

  • JOIN ( SELECT ... )没有使其高效的索引
  • LEFT JOIN ( ... )请求在左表后评估子查询,从而请求重复计算子查询。
  • SELECT *(在您的子查询中)收集了大量未使用的内容。 (SELECT *中的EXISTS并不意味着要抓取所有内容; *只是占位符。)
  • EXISTS评估为1(真)或0(假),这似乎是你想要的。