在MySQL上查找重复行以获取多个值

时间:2015-02-24 18:46:12

标签: mysql duplicates

我几天来一直在研究这个问题。我还在这个论坛上查看了其他相关问题。我会感激一点帮助。我的表包含以下属性:

User_ID | Questions | Answers

每位用户有3个问题和3个答案。

我的目标:在所有3个问题和答案中找到与其他用户匹配的所有用户。这就是我的尝试:**自我加入**

Select t1* from MyTable t1 JOIN (Select t2.Questions, t2.Answer FROM MyTable t2 GROUP BY t2.Questions, t2.Answer Having Count(*)>1) u on u.Questions = t1.Questions AND u.Answer = t1.Answer;

查询工作正常,但这不是我想要的。我觉得我错过了一件小事:)

此致

2 个答案:

答案 0 :(得分:0)

您可以使用自联接和聚合来获取两个用户之间的重叠。唯一的另一个方面是确保重叠涵盖三个问题:

select m.user_id, m2.user_id
from mytable m join
     mytable m2
     on m.question = m2.question and
        m.answer = m2.answer and 
        m.user_id < m2.user_id
group by m.user_id, m2.user_id
having count(*) = 3;

答案 1 :(得分:0)

我会打电话给你的桌子测验。这有用吗?

select q1.User_ID, q2.User_ID
from
    Quiz as q1 inner join
    Quiz as q2
        on      q1.User_ID < q2.User_ID
            and q2.Questions = q1.Questions and q2.Answers = q1.Answers
group by q1.User_ID, q2.User_ID
having count(*) = 3

我对优化MySQL查询并不是很了解,但这可能会有所帮助:

select q1.User_ID, q2.User_ID
from
    Quiz as q1 inner join
    Quiz as q2
        q2.Questions = q1.Questions and q2.Answers = q1.Answers
group by q1.User_ID, q2.User_ID
having q1.User_ID < q2.User_ID and count(*) = 3