且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL选择并按值分组

更新时间:2023-01-30 08:35:52

我想不出任何函数或方法来直接获得一系列所需的等级.我唯一能想到的就是拥有一个表,其中包含允许的评分范围.

I can't think of any function, or methodology, to directly get a range of ratings like what you need. The only thing I can think of is to have a table containing the allowable range of ratings.

Table: AllowedRatings
rating
1
2
3
4
5
6
7
8
9
10

然后使用它对您的评分表进行子查询:

Then use this to do a subquery with your ratings table:

SELECT (SELECT COUNT(*) 
          FROM ratings 
         WHERE ratings.rating = AllowedRatings.rating 
           AND pid = '1'
       )
     , rating
FROM AllowedRatings
ORDER BY rating

我知道这也可以通过联接来完成,但是那会更复杂,而且老实说,我有点太累了,无法解决它,或者正确地设置了一个数据库来对其进行测试,但是子查询方法应该工作.

I know this could also be done by a join, but that would be more complicated, and I'm honestly a bit too tired to work it out, or set up a DB correctly to test it, but the subquery method should work.

此方法的优点是您可以为评级添加更多信息,例如说明(例如:1 = 'Sucks', 3 = 'Meh', 5 = 'Ok', 7 = 'Worthwhile', 10 = 'Amazing!')或更改范围,而无需编辑硬编码值

The advantage of this method is that you could put more information in for your ratings, like a description (eg: 1 = 'Sucks', 3 = 'Meh', 5 = 'Ok', 7 = 'Worthwhile', 10 = 'Amazing!') or change your range without having to edit hard-coded values