-1

有谁知道您将如何计算一个值在单个列中出现的总次数。

例如我的表看起来像:

user_id  |  liked_id   |   likes

   3             1           1   
   4             1           1

我想要做的是计算liked_id 匹配的likes 列的总数。

所以 like_id 1 有 2 个喜欢?

有人可以告诉我我该怎么做吗?

function count_likes() {
            global $connection;
            global $profile_id;
            $query = "SELECT likes, count(*) FROM ptb_likes GROUP BY liked_id";
            $count_likes_set = mysql_query($query, $connection);
            confirm_query($count_likes_set);
            return $count_likes_set;        
        }
4

3 回答 3

3

尝试这个:

SELECT liked_id, SUM(likes) FROM ptb_likes GROUP BY liked_id
于 2013-02-10T15:49:46.930 回答
1

你应该将它们分组liked_id

SELECT liked_id, count(*)  totalLikes
FROM ptb_likes 
GROUP BY liked_id
于 2013-02-10T15:50:08.603 回答
0

如果您只想要 like_id 为 1 的行数,

SELECT liked_id, COUNT(likes) FROM ptb_likes WHERE liked_id = 1;

如果你想要每个like_id的频率:

SELECT liked_id, COUNT(likes) FROM ptb_likes GROUP BY liked_id;

注意:不要使用 SUM,因为它会添加 like_id 的所有值,如果您的 like_id 大于 1,那么您的计数将是错误的。请改用计数。

于 2013-02-10T16:01:53.563 回答