2014-01-22 69 views
0

sqlfiddle这里之间的冲突次数:http://sqlfiddle.com/#!2/bde34MySQL查询,选择两个用户

小提琴数据包含:
冲突用户1有:用户1和用户2之间

总冲突的问题用户2:
冲突用户2具有与用户1:

我有一个查询选择已回答相同问题的用户之间的冲突总数。我所追求的是使之出现个别冲突计算用户1与用户2和用户2与用户1

参考:

表1:user_answers表(存储用户的答案和他们接受的asnwers的各种问题)

值得注意值存储是:

users id (column uid) 
question id for the question they are answering (column quid) 
answer to the question (column answer) 
acceptable answer storage #1 stores other acceptable answers for that user (column acceptable_1) 
acceptable answer storage #2 stores other acceptable answers for that user (column acceptable_2) 
acceptable answer storage #3 stores other acceptable answers for that user (column acceptable_3) 
acceptable answer storage #4 stores other acceptable answers for that user (column acceptable_4) 
importance of their answer (column importance) 

答案栏将存储在1和4

0之间的值

可接受的列保存与列位置一致的可接受答案。例如,用户1回答1,但会接受答案2和3.这将使acceptable_2 = 2和acceptable_3 = 3,留下acceptable_1和acceptable_2值为0. 当两个用户进行比较时,发生冲突输入了另一个没有输入可接受值的答案。

现在我有一个查询将抓住两个用户之间的冲突总数,但我无法获取个人计数。例如,与用户2相比,用户1特别具有多少冲突,反之亦然。

例如:

#select counts of BOTH users total conflicts 
SELECT COUNT(*) 
    FROM user_answers t1 
    JOIN user_answers t2 ON t1.uid > t2.uid AND t1.quid = t2.quid AND 
    (FIELD(t1.answer, t2.acceptable_1, t2.acceptable_2, t2.acceptable_3, t2.acceptable_4) = 0 OR 
    FIELD(t2.answer, t1.acceptable_1, t1.acceptable_2, t1.acceptable_3, t1.acceptable_4) = 0) 
    WHERE t1.importance <> 1 AND t2.importance <> 1 and t1.uid in (1, 2) AND t2.uid in (1, 2) 

该查询给我的用户1和用户2之间的总的冲突,但我一直没能得到各个比较计数。我曾尝试删除其中一个FIELD函数,以一次只尝试比较一个用户,但结果并非我期望的结果。

任何帮助表示赞赏。

+1

在你的小提琴,在#创建实例4 USER1与用户2,但用户2还与用户1冲突不冲突?所以总的conflit应该是4和2对于1 => 2和2对于2 => 1? – dagfr

+0

@dagfr是的,你是正确的,但总冲突应该是有冲突的全部问题。将更新并测试您的答案。 – Jared

回答

2

试试这个

select sum(case(FIELD(t1.answer, t2.acceptable_1, t2.acceptable_2, t2.acceptable_3,  t2.acceptable_4)) when 0 then 1 else 0 end) as conflict_1_over_2, 
sum(case(FIELD(t2.answer, t1.acceptable_1, t1.acceptable_2, t1.acceptable_3, t1.acceptable_4)) when 0 then 1 else 0 end) as conflict_2_over_1 
    FROM user_answers t1 
JOIN user_answers t2 ON t1.uid > t2.uid AND t1.quid = t2.quid 
    WHERE t1.importance <> 1 AND t2.importance <> 1 and t1.uid in (1, 2) AND t2.uid in (1, 2) 
1

你可以试试这一个了。

SELECT u1.uid as user,u2.uid as conflict_user, 
     sum(FIELD(u1.answer,u2.acceptable_1,u2.acceptable_2,u2.acceptable_3,u2.acceptable_4)=0) 
     as conflicts, 
     group_concat(IF(FIELD(u1.answer,u2.acceptable_1,u2.acceptable_2,u2.acceptable_3,u2.acceptable_4)=0,u1.quid,NULL)) 
     as conflicted_questions 
FROM user_answers u1 
INNER JOIN user_answers u2 ON u1.quid = u2.quid AND u1.uid != u2.uid 
GROUP BY user,conflict_user 

sqlFiddle