我们怎样才能找到有多少用户在轮询中选择了相同的答案,以及在mysql查询中有多少问题是相同的。 这是我正在运行查询的表格。
id questionid answerid userid
1 1762 3514 156
2 1761 3512 156
3 1760 3511 156
4 1759 3509 156
5 1762 3514 157
6 1761 3513 157
7 1760 3510 157
8 1759 3509 157
9 1762 3514 158
10 1761 3512 158
11 1760 3511 158
12 1759 3509 158
我试过了
SELECT A.*
FROM sameanswers AS A
INNER JOIN (SELECT questionid, answerid
FROM sameanswers
GROUP BY questionid, answerid
HAVING COUNT(*) > 1) as B
ON A.questionid = B.questionid AND A.answerid = B.answerid
我的预期输出是有多少用户有相同的选择和多少问题。 例如,2个用户在2个问题上有相同的答案。
答案 0 :(得分:0)
如果我理解正确,您需要一份有关某人已回答的所有问题的清单,以及使用相同答案回答相同问题的其他人的清单。
使用子查询的粗略方式: -
SELECT A.*, b.others_count
FROM sameanswers AS A
LEFT OUTER JOIN
(
SELECT questionid, answerid, COUNT(*) AS others_count
FROM sameanswers
WHERE userid != 156
GROUP BY questionid, answerid
) as B
ON A.questionid = B.questionid AND A.answerid = B.answerid
WHERE A.userid = 156
或使用普通联接: -
SELECT A.id, A.questionid, A.answerid, A.userid, COUNT(B.id)
FROM sameanswers AS A
LEFT OUTER JOIN sameanswers AS B
ON A.questionid = B.questionid AND A.answerid = B.answerid AND A.userid != B.userid
WHERE A.userid = 156
GROUP BY A.id, A.questionid, A.answerid, A.userid;
SQL的小提琴: -
http://www.sqlfiddle.com/#!2/07670/9
编辑 - 这应该为您的新要求得到结果: -
SELECT B.userid, COUNT(B.id) AS match_count
FROM sameanswers AS A
LEFT OUTER JOIN sameanswers AS B
ON A.questionid = B.questionid
AND A.answerid = B.answerid
AND A.userid != B.userid
WHERE A.userid = 156
GROUP BY B.userid
ORDER BY match_count DESC LIMIT 1;