mySQL查询比较行和列

时间:2012-01-18 23:13:09

标签: mysql

我有一个测验用户答案数据库,其中包含8个问题。 Q1-Q8都是他们自己的专栏,我想比较所有的行,并为每个回答相同且至少5个问题的人提供一个数字。

enter image description here

所以在这里,第5行和第6行将计为2.基本上我正在尝试为每个回答至少5个问题的人提供一个数字。这可能是mySQL查询吗?

编辑:

enter image description here

这里用户输入D B D A B C D B,与2个类似回答的测验相匹配。这里的查询将返回2的计数。

2 个答案:

答案 0 :(得分:3)

如果我们仅使用您的单行D B D A B C D B进行测试,我们可以使用以下示例:

SELECT * FROM `answers` WHERE  ((CASE WHEN q1 = 'D' THEN 1 ELSE 0 END) +     
(CASE WHEN q2 = 'B' THEN 1 ELSE 0 END) +     
(CASE WHEN q3 = 'D' THEN 1 ELSE 0 END) +         
(CASE WHEN q4 = 'A' THEN 1 ELSE 0 END) +     
(CASE WHEN q5 = 'B' THEN 1 ELSE 0 END) +     
(CASE WHEN q6 = 'C' THEN 1 ELSE 0 END) +     
(CASE WHEN q7 = 'D' THEN 1 ELSE 0 END) +         
(CASE WHEN q8 = 'B' THEN 1 ELSE 0 END)) >= 5;        

但是,如果我们想要更进一步并根据表中的其他答案测试每个答案,我们可以使用以下语句:

SELECT *, (SELECT COUNT(answer_sub.idanswers) FROM `answers` answer_sub     
WHERE ((CASE WHEN answer_sub.q1 = a.q1 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q2 = a.q2 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q3 = a.q3 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q4 = a.q4 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q5 = a.q5 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q6 = a.q6 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q7 = a.q7 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q8 = a.q8 THEN 1 ELSE 0 END)) >= 5     
AND answer_sub.idanswers <> a.idanswers) as matching    
FROM `answers` a    
WHERE (SELECT COUNT(answer_sub.idanswers) FROM `answers` answer_sub     
WHERE ((CASE WHEN answer_sub.q1 = a.q1 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q2 = a.q2 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q3 = a.q3 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q4 = a.q4 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q5 = a.q5 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q6 = a.q6 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q7 = a.q7 THEN 1 ELSE 0 END) +     
(CASE WHEN answer_sub.q8 = a.q8 THEN 1 ELSE 0 END)) >= 5     
AND answer_sub.idanswers <> a.idanswers) > 0    

答案 1 :(得分:0)

因为MySQL中FALSE0TRUE1

SELECT COUNT(*)
FROM quiz
WHERE ( (q1=@q1) + (q2=@q2) + (q3=@q3) + (q4=@q4)
      + (q5=@q5) + (q6=@q6) + (q7=@q7) + (q8=@q8) 
      ) >= 5