douhui9192 2010-11-18 16:57
浏览 27
已采纳

从数据库返回平均评级(SQL)

I'm trying to create a rating system, where the user can rate pictures/videos/audio etc. I have two tables at the moment

Table: products
Cols:  product_id[PK] | name | category | type | link

This is the products table and contains information about the products. If you're confused by products, think of the "product" as the image/video/audio, I named it like this simply for allowing me to understand it easier. The second table is the ratings

Table: product_ratings
Cols:  rating_id[PK] | rating | product_id | timestamp

This table stores information about the rating the user has given.

I want a page where it will display the highest rating (on average) for all "products". So far, I've looked through SA, and found the follow piece of code:

SELECT
p.product_id, p.name,
AVG(pr.rating) AS rating_average
FROM products p
INNER JOIN product_ratings pr
ON pr.product_id = p.product_id
WHERE p.product_id = 1

This just returns the average rating for a specific product_id, How would I go about getting ALL the product_ids and their average rating, and how would I find the highest one via PHP?

I've tried:

WHERE p.product_id < 1 AND p.product_id < 30

But this just returns product_id of 2, with it's name and average_rating, which I don't understand.

Guidance/links to material are welcome

  • 写回答

3条回答 默认 最新

  • drurhg37071 2010-11-18 16:59
    关注
    SELECT
        p.product_id,
        p.name,
        AVG(pr.rating) AS rating_average
    FROM products p
    INNER JOIN product_ratings pr
    ON pr.product_id = p.product_id
    GROUP BY p.product_id
    ORDER BY rating_average DESC
    LIMIT 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了