简体   繁体   English

使用MySQL和PHP计算字段中每个值的数量

[英]Count how many of each value from a field with MySQL and PHP

I've seen that question several times but I can't find out how to display the result. 我已经多次看过这个问题,但我找不到如何显示结果。 I have a movie database and I would like the count of each genre of movie in my top menu in a single MySQL query so my menu would display like this: 我有一个电影数据库,我希望在一个MySQL查询的顶级菜单中计算每种类型的电影,所以我的菜单会显示如下:

Total Movies (300)
Drama (50)
Comedy (75)
Thriller (30)
...and so on...

I've found some MySQL query on this site but no one specify HOW to handle the counts after the SQL query. 我在这个站点上发现了一些MySQL查询,但没有人指定如何处理SQL查询后的计数。 Something like this would probably work: 像这样的东西可能会起作用:

select genre, count(*) from movies group by genre

But how do I display the count for each value afterwards? 但是如何在之后显示每个值的计数? Thank you very much! 非常感谢你!

Alias the count part so you have an easily accessible column name: 别名计数部分,以便您可以轻松访问列名:

SELECT genre, count(*) AS nb_movies FROM movies GROUP BY genre

then you can access it like $row['nb_movies'] . 然后你可以像$row['nb_movies']一样访问它。

Without the alias the aggregate column takes the name of the aggregate function call which produced it, so in your case it would be accessed like $row['count(*)'] . 如果没有别名,聚合列将获取生成它的聚合函数调用的名称,因此在您的情况下,它将像$row['count(*)']一样被访问。

Try 尝试

select genre, count(*) AS total from movies group by genre

Use total as your count for eg. 使用总数作为例如。

echo $result['total'];

Try this, 试试这个,

SELECT genre, count(*) AS total_genre_movies FROM movies GROUP BY genre

Now you can access like $result['total_genre_movies'] 现在您可以访问$result['total_genre_movies']

It's easier if you alias the result of count(*) 如果别名计数结果(*)会更容易

select genre, 
       count(*) as total
  from movies 
 group by genre

Then you can access it as $row['total'] when you fetch the result into $row in exactly the same way you'd reference $row['genre'] 然后,当您将结果提取到$row ,您可以将其作为$row['total']访问,其方式与引用$row['genre']完全相同

   select genre, count(*) as genre_count from movies group by genre

现在您可以访问$ result ['genre_count']

Try this, 试试这个,

$result = mysql_query("select genre, count(*) as genre_count from movies group by genre");

while($row = mysql_fetch_array($result)) {

   $genre       = $row['genre'];
   $genre_count = $row['genre_count'];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM