第一种方法:-
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
两个查询返回相同的结果,但只是想知道我应该遵循哪种方法以及哪种方法更有效。记录集将包含数百万条记录,所以我想使用最好的方法。或者我正在工作,请纠正我。预先感谢您。
解释第一种方法的声明
最佳答案
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(假),这似乎正是您想要的。
关于mysql - 这是执行 MySQL 查询的最佳/有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35595385/