MYSQL查询显示类别中最受欢迎的条目

时间:2011-12-15 10:11:17

标签: php mysql join

我有一个存储人们兴趣的数据库我有一个查询,通过我的兴趣表,并根据字段categoryID列出最受欢迎的兴趣。但是我可以显示的只是categoryID而不是类别名称,我如何在表格类别中链接以显示类别名称而不是ID?

这是我的查询和输出:

PHP:

$interestCatPopular = "SELECT interest_desc, categoryID, MAX(num_in_cat) AS num_in_cat 
FROM
(
   SELECT interest_desc, categoryID, COUNT(categoryID) AS num_in_cat
   FROM interests
   GROUP BY interest_desc, categoryID
 ) subsel 
 GROUP BY interest_desc, categoryID";
 $mostPopularInterest = mysql_query($interestCatPopular) or die(mysql_error());

 $arrayResults = array();
 while ($row = mysql_fetch_assoc($mostPopularInterest)) {
 $arrayResults[] = $row;
 }

 foreach ($arrayResults as $result) {
 echo "{$result['interest_desc']} was the most popular in category   {$result['categoryID']}    with {$result['num_in_cat']} occurrences\n";
 }

输出:

足球是第9类中最受欢迎的,10次出现山羊是第4类中最受欢迎的,1次出现菲尔是第2类中最受欢迎的59次事件

由于

更新

表格结构 -
兴趣:

 Field  Type    Collation   Attributes  Null    Default Extra   Action
interestID  int(11)         No  None    AUTO_INCREMENT                          
name    varchar(100)    utf8_general_ci     No  None                                 
categoryID  varchar(30) utf8_general_ci     No  None                                 
interest_desc   text    utf8_general_ci     No  None                                 
date    timestamp           No  CURRENT_TIMESTAMP   

类:

Field   Type    Collation   Attributes  Null    Default Extra   Action
categoryID  int(11)         No  None    AUTO_INCREMENT                          
category_desc   varchar(100)    utf8_general_ci     No  None                                                        

1 个答案:

答案 0 :(得分:1)

为什么你不加入这样的两个表:

SELECT interest_desc, 
       (
         select categoryName 
         from categories where categoryID = subsel.categoryId
       ), MAX(num_in_cat) AS num_in_cat 
FROM ( 
      SELECT interest_desc, categoryID, 
      COUNT(categoryID) AS num_in_cat 
      FROM interests GROUP BY interest_desc, categoryID
) 
subsel 
GROUP BY interest_desc, categoryID