SQL语句显示每个用户选择和一个用户选择之间的差异

时间:2012-01-11 10:53:42

标签: php sql

基本上我需要创建输出TOP表,通过比较他们的点和管理员点来安排用户。 例如:

User3 | 0 //Everything was as admin had.
User5 | 3 //One song had 2 points different from admin and one was off by one
ect.

在我的数据库中,我有三个表:

Table: rating

+------------+---------+----------+---------+ 
| rating_id  | user_id | song_id  | points  | 
+------------+---------+----------+---------+ 
| 1          | 1       | 4        | 0       | 
| 2          | 1       | 3        | 1       | 
| 3          | 3       | 2        | 3       | 
| 4          | 4       | 2        | 2       | 
| 5          | 2       | 1        | 4       |


Table: songs

+---------------+------------+ 
| song_name_id  | song_name  | 
+---------------+------------+ 
| 1             | Song1      | 
| 2             | Song2      | 
| 3             | Song3      | 
| 4             | Song4      | 
| 5             | Song5      | 

Table: users

+----------+----------+----------+
| id       | username | password |
+----------+----------+----------+
| 1        | User1    | passw    |
| 2        | User2    | wordp    |
| 3        | User3    | somet    |
| 4        | User4    | hings    |

它应该是这样的(不是任何编程语言):

Compare user_id > 1 with user_id=1 //Let's say that the comparable admin is user_id=1
$result= ABS(user.points-admin.points)++;

把它放到数组中:

username => result

然后当我按结果对这个数组进行排序时,我可以将它打印为顶级表格 - 谁得到了最接近管理员的结果!

我尝试了几种不同的解决方案但从未得到正确的结果。

有人能帮助我吗?

更新

谢谢!

使用JOIN,结果为:

+------------+---------+----------+---------+-----------+
| song_id    |song_name| user_id  |username |rating_diff|
+------------+---------+----------+---------+-----------+ 
| 1          | Song1   | 1        | admin   | 0         | 
| 2          | Song2   | 1        | admin   | 0         |
...etc...

使用LEFT JOIN,结果为:

+------------+---------+----------+---------+-----------+
| song_id    |song_name| user_id  |username |rating_diff|
+------------+---------+----------+---------+-----------+ 
| 1          | Song1   | 11       | user2   | NULL      | 
| 1          | Song1   | 10       | user1   | NULL      |
| 1          | Song1   | 12       | user3   | NULL      |
| 1          | Song1   | 1        | admin   | 0         |
| 2          | Song2   | 11       | user2   | NULL      | 
| 2          | Song2   | 10       | user1   | NULL      |
| 2          | Song2   | 12       | user3   | NULL      |
| 2          | Song2   | 1        | admin   | 0         |

..etc..

所以..出了点问题,rating_diff不起作用。

1 个答案:

答案 0 :(得分:1)

假设您希望逐个歌曲进行比较(而不是所有歌曲的总数或平均值),请尝试:

select r.song_id,
       s.song_name,
       r.user_id,
       u.username,
       abs(r.points - r1.points) rating_diff
from rating r
join songs s on r.song_id = s.song_name_id
join users u on r.user_id = u.id
join rating r1 on r.song_id = r1.song_id and r1.user_id = 1
order by s.song_name, abs(r.points - r1.points)

这应该按歌曲名称排序输出,然后按管理员点数和用户点数之间的差异排序。 (如果您无法保证每首歌曲的管理员评分,请将rating r1上的联接更改为左联接。)