如何将“变量”传递给mysql JOIN(SELECT)子查询

时间:2018-11-28 06:49:56

标签: mysql subquery

我需要为每个评论计数,此查询有问题。 查询大约需要3秒的时间才能获得100万条评论和300万条评论

据我了解,问题在于mysql对所有评论的所有投票计数

F5

那么如何在子查询中传递UC_Code这样呢?

SELECT com.*, cv.UC_Vote, cv.UC_Vote_Neg, cv.UC_Vote_Pos
    FROM Comments AS com
        LEFT JOIN (
            SELECT SUM(Vote) AS UC_Vote, SUM(IF(Vote < 0, Vote, 0)) AS UC_Vote_Neg, SUM(IF(Vote > 0, Vote, 0)) AS UC_Vote_Pos, UC_Code FROM CommentsVote
            GROUP BY UC_Code
        ) AS cv ON cv.UC_Code = com.UC_Code
    WHERE
       com.Blo_Code = $blocode AND com.UC_Status = 1

1 个答案:

答案 0 :(得分:0)

我知道了! 这样做

SELECT com.*, UNIX_TIMESTAMP(com.UC_Time) AS UC_UnixTime, com.UC_Code AS CommentId, com.UC_Parent AS ParentId, cc.UC_Complain,
                              (SELECT SUM(Vote) FROM CommentsVote WHERE UC_Code = com.UC_Code GROUP BY UC_Code) AS UC_Vote,
                              (SELECT SUM(IF(Vote < 0, Vote, 0)) FROM CommentsVote WHERE UC_Code = com.UC_Code GROUP BY UC_Code) AS UC_Vote_Neg,
                              (SELECT SUM(IF(Vote > 0, Vote, 0)) FROM CommentsVote WHERE UC_Code = com.UC_Code GROUP BY UC_Code) AS UC_Vote_Pos
                              FROM Comments AS com
                                LEFT JOIN (
                                  SELECT COUNT(us_id) AS UC_Complain, UC_Code FROM CommentsComplain
                                  GROUP BY UC_Code
                                ) AS cc ON cc.UC_Code = com.UC_Code
                              WHERE
                                com.Blo_Code = 473626 AND com.UC_Status = 1