【问题标题】:which is the best / efficient way to execute MySQL query这是执行 MySQL 查询的最佳/有效方式
【发布时间】:2016-06-06 08:14:31
【问题描述】:

第一种方法:-

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

两个查询都返回相同的结果,但只想知道我应该遵循哪种方法以及哪种方法更有效。记录集将包含数百万条记录,所以我想使用最好的方法。或者我正在工作,请纠正我。提前谢谢你。

解释语句第一种方法

解释语句第二种方法

解释陈述第一种方法

【问题讨论】:

  • 做一些基准测试并使用 mysql explain 来调查索引列的使用情况。如果没有看到您的实际表定义,很难给出适当的建议。

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


【解决方案1】:
    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 *(在您的子查询中)正在收集许多未使用的东西。 (EXISTS 中的SELECT * 并不意味着获取所有内容;* 只是一个占位符。)
  • EXISTS 计算结果为 1(真)或 0(假),这似乎是您想要的。

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多