![](/img/trans.png)
[英]Best way to connect to MySQL and execute a query? (probably with Dapper)
[英]which is the best / efficient way to execute MySQL query
第一種方法:
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(假),這似乎是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.