MySQL计数问题

时间:2010-08-09 00:13:58

标签: php mysql

我一直在尝试计算标签输入数据库的次数,并将其与标签一起输入的次数显示在数据库中,就像在StackOverflow上一样,但我似乎无法能够做到有人可以帮助我吗?

到目前为止,我可以获得标签,但不是计数。

提前感谢您的帮助!

这是我的MySQL& PHP代码。

$dbc = mysqli_query($mysqli,"SELECT tags.*, posts_tags.* 
                             FROM tags 
                             INNER JOIN posts_tags ON tags.id = posts_tags.tag_id
                             GROUP BY tags.tag
                             ORDER BY tags.tag ASC");

if (!$dbc) {
    print mysqli_error($mysqli);
}

while($row = mysqli_fetch_assoc($dbc)) {
    $tag = $row['tag'];

    echo '<a href="http://localhost/tags/">' . $tag . '</a>';

}

2 个答案:

答案 0 :(得分:3)

您可能需要尝试以下操作:

SELECT      tags.tag, COUNT(DISTINCT posts_tags.post_id) as number_of_tags
FROM        tags 
INNER JOIN  posts_tags ON tags.id = posts_tags.tag_id
GROUP BY    tags.tag
ORDER BY    tags.tag ASC;

测试用例:

CREATE TABLE tags (id int, tag varchar(10));
CREATE TABLE posts_tags (post_id int, tag_id int);

INSERT INTO tags VALUES (1, 'javascript');
INSERT INTO tags VALUES (2, 'php');
INSERT INTO tags VALUES (3, 'mysql');

INSERT INTO posts_tags VALUES (1, 1);
INSERT INTO posts_tags VALUES (2, 2);
INSERT INTO posts_tags VALUES (3, 1);
INSERT INTO posts_tags VALUES (4, 2);
INSERT INTO posts_tags VALUES (5, 3);
INSERT INTO posts_tags VALUES (6, 1);
INSERT INTO posts_tags VALUES (7, 1);
INSERT INTO posts_tags VALUES (8, 2);
INSERT INTO posts_tags VALUES (9, 2);
INSERT INTO posts_tags VALUES (10, 1);

结果:

+------------+----------------+
| tag        | number_of_tags |
+------------+----------------+
| javascript |              5 |
| mysql      |              1 |
| php        |              4 |
+------------+----------------+
3 rows in set (0.00 sec)

答案 1 :(得分:2)

如果你想要一个标签列表,包括那些计数为零的标签,请使用LEFT JOIN:

   SELECT t.tag, 
          COALESCE(COUNT(DISTINCT pt.post_id), 0) AS tag_count
     FROM TAGS t
LEFT JOIN POSTS_TAGS pt ON pt.tag_id = t.id
 GROUP BY t.tag
 ORDER BY t.tag 

如果您只想查看已使用过一次或多次的内容,请使用INNER JOIN:

  SELECT t.tag, 
         COUNT(DISTINCT pt.post_id) AS tag_count
    FROM TAGS t
    JOIN POSTS_TAGS pt ON pt.tag_id = t.id
GROUP BY t.tag
ORDER BY t.tag