我有4张桌子:
record_id first_name last_name
1 John Smith
2 Jim Brown
3 Jane Goodall
record_id poll_question
1 What is your age?
2 What is your occupation?
record_id poll_id option_text
1 1 16-20
2 1 21-25
3 2 builder
4 2 technician
record_id user_id poll_id option_id
1 1 1 1
2 1 2 1
3 2 1 2
4 2 2 1
给定指定用户,如何让所有为指定用户回答的民意调查选择相同选项的其他用户。
理想情况下,它会根据回答的问题提供一个下降的用户列表,即投票完全相同的用户将位于顶部,直至用户没有共同的答案。
答案 0 :(得分:4)
SELECT u.first_name, u.last_name, v.Answers
FROM Users AS u
LEFT JOIN (
SELECT pv.user_id AS user, COUNT(*) AS Answers
FROM PollVotes AS pv
WHERE ((poll_id, option_id) IN
(
SELECT poll_id, option_id
FROM PollVotes
WHERE user_id = YOURUSER
))
AND pv.user_id != YOURUSER
GROUP BY pv.user_id
) AS v
ON u.record_id = v.user
WHERE u.record_id != YOURUSER
ORDER BY v.Answers DESC
内部查询选择与所选用户具有相同(poll_id, option_id)
组合的所有用户。每个用户的行数是常见答案的数量。与用户表的左连接是包括在结果中没有共同答案的用户。
答案 1 :(得分:0)
这是另一种方法:
SELECT u1.record_id, u1.first_name, u1.last_name, u2.record_id comp_record_id, u2.first_name comp_first_name, u2.last_name comp_last_name, u1.options FROM (
SELECT u.record_id, u.first_name, u.last_name, GROUP_CONCAT(pv.poll_id,'.', pv.option_id ORDER BY pv.poll_id, pv.option_id) options
FROM users u
INNER JOIN poll_votes pv ON pv.user_id = u.record_id
GROUP BY u.record_id
) u1
INNER JOIN (
SELECT u.record_id, u.first_name, u.last_name, GROUP_CONCAT(pv.poll_id,'.', pv.option_id ORDER BY pv.poll_id, pv.option_id) options
FROM users u
INNER JOIN poll_votes pv ON pv.user_id = u.record_id
GROUP BY u.record_id
) u2 ON u1.options = u2.options AND u1.record_id <> u2.record_id
WHERE u1.record_id = 1;
两个内部查询是相同的,实际上可以转换为视图。外部查询只是将问题/答案列表中的两个连接起来以获得匹配。