0

2 つのテーブルがあり、1 つはクイズの質問を定義し、もう 1 つはクイズの質問に対する回答のテーブルです。

最初のテーブルの構造は次のとおりです。

questionID attribute value
1          title     some textQ1
1          option1   some text
1          option2   some text
1          option3   some text
1          correct   2
2          title     some textQ2
2          option1   some text
2          option2   some text
2          option3   some text
2          correct   1,2

2 番目の表には、ユーザーからの回答があります

userID   questionID   value
user1    1            3
user2    1            2
user3    1            2
user3    2            1
user3    2            2
user2    2            3

次に、各ユーザーのスコアを取得できるようにしたいと思います。たとえば、正解ごとに 1 ポイントです。

したがって、データセットは次のようになります

user    score
user3   3
user2   1
user1   0

複数の質問エントリと複数のユーザーを許可する 1 つのクエリでこれを行うことは可能ですか?

どうもありがとう

4

1 に答える 1

0

あなたが探しているのはこれでしょうか?

SQLデモ

select r.userid, 
sum(case when find_in_set(r.value, q.value) then 1
     else 0
     end) as score   
from responses r
left join questions q
on r.questionid = q.questionid
where q.attribute = 'correct'
group by r.userid
order by score desc
;

| USERID | SCORE |
------------------
|  user3 |     3 |
|  user2 |     1 |
|  user1 |     0 |
于 2013-02-26T12:05:20.810 に答える