MYSQL - 计算单个表中的差异

时间:2012-06-26 14:11:33

标签: mysql

我正在寻找一种计算单个表中整数之间差异的方法。

我正在计划一个看起来像这样的MYSQL表:

user    question    answer

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

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

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

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

每个用户(在此示例中)已回答了5个问题,给出了1到5分的答案。

我想要解决的是用户2,3和4中的哪一个给出了与用户1提供的答案最相似的答案。

我想到的是计算每个用户为每个问题给出的答案与用户1的答案之间的差异,然后将这些差异加起来。

添加后编号最小的用户与用户1最相似。

我很遗憾地说,我真的不知道从哪里开始构建一个有效地执行此操作的查询,并且想知道是否有人能指出我正确的方向? 我也愿意接受任何更好或更合理的方法来建立相同的结果。

2 个答案:

答案 0 :(得分:0)

SELECT SUM(ABS(t2.answer - t1.answer)) AS total_diff, t2.user 
FROM my_table AS t1 
LEFT JOIN my_table AS t2 USING(question)
WHERE t1.user = 1 AND t2.user != t1.user
GROUP BY t2.user
ORDER BY total_diff ASC

结果:

total_diff  user 
2       4
4       2
4       3

答案 1 :(得分:0)

SELECT 
yt1.user,
SUM(CASE WHEN yt1.answer = yt2.answer THEN 1 ELSE 0 END) AS howMuchAnswersInCommon
FROM yourTable yt1
INNER JOIN yourTable yt2 ON yt1.question = yt2.question 
WHERE yt2.user = 1 AND yt1.user != 1
GROUP BY yt1.user
ORDER BY howMuchAnswersInCommon DESC 
;

这将为您提供最常见的用户1答案。

测试数据:

/*
create table yourTable (user int, question int, answer int);
insert into yourTable values 
(1,       1,           3),
(1,       2,           3),
(1,       3,           2),
(1,       4,           5),
(1,       5,           1),

(2,       1,           2),
(2,       2,           3),
(2,       3,           1),
(2,       4,           5),
(2,       5,           3),

(3,       1,           3),
(3,       2,           3),
(3,       3,           4),
(3,       4,           5),
(3,       5,           3),

(4,       1,           5),
(4,       2,           3),
(4,       3,           2),
(4,       4,           5),
(4,       5,           1);
*/

输出:

user    howMuchAnswersInCommon
4           4
3           3
2           2