3

我有一个媒体文件表和第二个媒体文件评级表。

我应该使用什么 SQL 语句从第一个表中选择第二个表中正负评级比率最高的媒体文件?

下表包含与每个媒体文件相关的信息。

表:“媒体”

| mediaID |
-----------
|       3 |
|      22 |

鉴于下表;媒体文件#3 的评分为 2/3 或 66%,#22 的评分为 1/2 或 50%。

表:“评分”

| mediaID | rating |
--------------------
|       3 |      1 |
|       3 |      1 |
|       3 |      0 |
|      22 |      1 |
|      22 |      0 |

任何帮助将不胜感激:) 我已经得到:

SELECT media.mediaID, (
    (SELECT COUNT(CASE WHEN rating =1 THEN 1 END ) Positive FROM ratings)
        /
    (SELECT COUNT( mediaID ) FROM ratings )
) AS percent
FROM ratings, media
WHERE media.mediaID = ratings.mediaID
GROUP BY mediaID

此外,在我看来,两个或多个媒体文件之间的正票数与总票数的比率可能相同。在那种情况下,我怎么能让 MySQL 只选择一个呢?

4

1 回答 1

1

Try this

    select r.mediaid, 
       count(*) as total_rows, 
       sum(rating) as id_sum,
       SUM(rating)/count(*) AS score
    from rating r, media m
    where r.mediaid=m.mediaid
    group by r.mediaid

If you want to report only those records with a score above a threshold such as 0.75 then add the 'having' clause

 select r.mediaid, 
        count(*) as total_rows, 
        sum(rating) as id_sum,
        SUM(rating)/count(*) AS score
   from rating r, media m
  where r.mediaid=m.mediaid
  group by r.mediaid
  having score > .75  

Here's a demo SQL Fiddle

After Comment

One way is to sort by scores desc and then limit to 1 record like this SQL Fiddle#2

    select r.mediaid, 
     count(*) as total_rows, 
     sum(rating) as id_sum,
     SUM(rating)/count(*) AS score
from rating r, media m
 where r.mediaid=m.mediaid
 group by r.mediaid
order by score desc limit 1
于 2013-09-20T19:51:05.777 回答