duangong937906 2012-06-21 14:02
浏览 33
已采纳

具有特定参数的MySQL / PHP平均列值

I have a surprisingly basic question; I thought the answer was going to be more straightforward regarding Averaging columns. Here is my table with sample values:

Table: ratings

id, rating, item_id

Sample data

1, 5, 3
2, 1, 2
3, 2, 3
4, 4, 4 
5, 1, 2

What if I want to get the average rating of the item_id's marked "3"

The real answer would be 2.5 since there is a 3 with a1, and another with a 5.

Here is the query I believe:

 SELECT avg(rating) as average FROM ratings;

How do I specify ONLY the ratings with an item_id of 3? Do I use WHERE? GROUP BY? something else?

And the second part of the question: How do I output this into a single variable?

  • 写回答

3条回答 默认 最新

  • drox90250557 2012-06-21 14:18
    关注

    You simply need to specify a WHERE clause:

    SELECT AVG(rating) AS average
    FROM ratings
    WHERE item_id = 3
    -- returns 1 row
    

    If you want to get averages of entire data grouped by item_id you can use GROUP BY:

    SELECT item_id, AVG(rating) AS average
    FROM ratings
    GROUP BY item_id
    -- returns as many rows as the number of distinct item_ids
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部