sql计算错误的喜欢数量

时间:2014-07-03 14:23:11

标签: mysql sql

我写了一个sql语句,除了所有其他列之外,还应该返回评论的数量和某个帖子的喜欢数量。当我不想尝试分享它的次数时,它工作得很好。当我试图获得共享的时间而不是它返回一个错误的数字,似乎是股票和喜欢的数量或类似的东西。这是代码:

SELECT 
    [...], 
    count(CS.commentId) as shares, 
    count(CL.commentId) as numberOfLikes
FROM 
    (SELECT * 
     FROM accountSpecifics 
     WHERE institutionId= '{$keyword['id']}') `AS`
INNER JOIN 
    account A ON A.id = `AS`.accountId
INNER JOIN 
    comment C ON C.accountId = A.id 
LEFT JOIN 
    commentLikes  CL ON C.commentId = CL.commentId
LEFT JOIN 
    commentShares  CS ON C.commentId = CS.commentId
GROUP BY 
    C.time
ORDER BY 
    year, month, hour, month

您是否也可以告诉我您是否认为这是一个有效的SQL语句,或者您是否会采用不同的方式?谢谢!

2 个答案:

答案 0 :(得分:0)

快速修复:

SELECT 
    [...], 
    count(DISTINCT CS.commentId) as shares, 
    count(DISTINCT CL.commentId) as numberOfLikes

更好的方法:

SELECT [...]
     , Coalesce(shares.numberOfShares, 0) As numberOfShares
     , Coalesce(likes.numberOfLikes  , 0) As numberOfLikes
FROM   [...]
 LEFT
  JOIN (
        SELECT commentId
             , Count(*) As numberOfShares
        FROM   commentShares  
        GROUP
            BY commentId
       ) As shares
    ON shares.commentId = c.commentId
 LEFT
  JOIN (
        SELECT commentId
             , Count(*) As numberOfLikes
        FROM   commentLikes
        GROUP
            BY commentId
       ) As likes
    ON likes.commentId = c.commentId

答案 1 :(得分:0)

请改为:

SELECT 
[...], 
(select count(*) from commentLikes CL where C.commentId = CL.commentId) as shares, 
(select count(*) from commentShares CS where C.commentId = CS.commentId) as numberOfLikes
FROM 
(SELECT * 
 FROM accountSpecifics 
 WHERE institutionId= '{$keyword['id']}') `AS`
INNER JOIN account A ON A.id = `AS`.accountId
INNER JOIN comment C ON C.accountId = A.id 
GROUP BY C.time
ORDER BY year, month, hour, month

如果您使用JOIN,那么您将获得一个结果集,并且COUNT(任何字段)只会对行进行计数并始终计算相同的内容,在这种情况下是错误的。子查询是您需要的。祝你好运!

编辑:如下所示,count(不同的某些)也可以正常工作,但它使数据库做的工作超出了你想要最终得到的答案所需的工作量。 / p>