将帖子计为类别PHP& MYSQL

时间:2016-04-18 05:56:50

标签: php mysql count categories

我有这段代码......

$lesson = mysql_query("SELECT * FROM categories WHERE gr='exrcs' ORDER BY title");
$flesson = mysql_fetch_array($lesson);
do {
    printf("<a href='exrcs?cat=%s'>%s</a>",$flesson['id'],$flesson['title']);
   } while ($flesson = mysql_fetch_array($lesson));

此代码将&#34; HTML, CSS, PHP&#34; 和其他...

但我想要&#34; HTML (2), CSS (14), PHP(8)&#34; 以及其他...

这里有(2),(14),(8)个类别的帖子

3 个答案:

答案 0 :(得分:1)

更新您的查询:

SELECT title, count(id) total FROM categories WHERE gr='exrcs' group by title ORDER BY title

SELECT concat(title,' (', count(id) ,')') as title FROM categories WHERE gr='exrcs' group by title ORDER BY title

答案 1 :(得分:0)

使用count和group by

"SELECT cat as title , count(*)  FROM categories 
WHERE gr='exrcs' group by title  ORDER BY title"

答案 2 :(得分:0)

"SELECT CONCAT(C.title,'(',COUNT(*),')') FROM categories C INNER JOIN post P ON C.ID= P.cat_id GROUP BY c.title"