2010-08-09 40 views
4

我一直在計算一個標籤被輸入到數據庫中的次數,並顯示它已經與標籤一起輸入到數據庫中的次數,就像這裏的StackOverflow一樣,但我可以' t似乎能夠做到這一點,有人可以幫助我嗎?MySQL計數問題

到目前爲止,我可以得到標籤,但不是數量。

在此先感謝您的幫助!

這是我的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>'; 

} 

回答

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) 
+0

感謝它的工作:) – helpME 2010-08-09 00:23:33

+0

@helpME幫助:還檢查了OMG小馬'的答案,如果你想顯示標籤的計數是'0'。 – 2010-08-09 00:29:21

+0

@Daniel Vassallo但是如果我計數tag.id,我的計數將永遠是1不是嗎? – helpME 2010-08-09 00:40:19

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 
+0

是的,我忘了提及'LEFT JOIN' :) – 2010-08-09 00:28:42

+1

@Daniel Vassallo:有人必須讓你的腳趾:) – 2010-08-09 00:30:03

+0

你爲什麼要把COUNT改成COUNT(DISTINCT tag_id)'?因爲你是按標籤分組的,所以不會總是顯示'1'...'GROUP_CONCAT(pt.tag_id)'會返回類似'1,1,1,1,1'的東西。 – 2010-08-09 00:56:19