我有一个数据库,其中存储了一个包含用户信息的表、一个包含测试(答案和分数)的表以及一个包含用户对每个问题的答案的表。每题总计1分,可以有一个或多个正确答案。如果所有的答案都是正确的,而用户只检查了一个,他将只得到 0.25 分。 我想查询每个用户的总分,但我没有找到好的方法。
用户表:
+--------+------------+-----------+-------------------+------------+--------+
| userID | first_name | last_name | email | password | points |
+--------+------------+-----------+-------------------+------------+--------+
| 1 | Jhon | Jhonny | jhon@yahoo.com | secretPass | 0 |
| 2 | Dan | Dan | dan@yahoo.com | 1234 | 0 |
| 3 | Dick | Pop | dd@yahoo.com | 123456 | 0 |
| 4 | Mihaela | Micky | mihaela@yahoo.com | pass12 | 0 |
+--------+------------+-----------+-------------------+------------+--------+
问题表: (1 表示答案很好——我们可以有多个正确答案)
+------------+--------------------------------------------------+---+---+---+---+
| questionID | question | a | b | c | d |
+------------+--------------------------------------------------+---+---+---+---+
| 1 | which of these are colors? | 1 | 0 | 0 | 1 |
| 2 | which of these are fruits? | 1 | 1 | 1 | 0 |
| 3 | which of these are programming language? | 0 | 1 | 1 | 0 |
| 4 | What is IPv6? | 0 | 0 | 0 | 1 |
+------------+--------------------------------------------------+---+---+---+---+
用户的答案表:(1表示用户选择了那个答案但可能不正确)
+------------+--------+---+---+---+---+
| questionID | userID | a | b | c | d |
+------------+--------+---+---+---+---+
| 1 | 1 | 1 | 1 | 0 | 0 |
| 2 | 1 | 1 | 1 | 1 | 0 |
| 1 | 3 | 1 | 0 | 1 | 1 |
| 1 | 4 | 1 | 1 | 1 | 0 |
| 3 | 1 | 1 | 0 | 1 | 1 |
| 4 | 1 | 1 | 0 | 1 | 1 |
| 1 | 2 | 1 | 1 | 0 | 0 |
| 2 | 2 | 0 | 1 | 0 | 1 |
| 3 | 2 | 0 | 1 | 1 | 1 |
| 4 | 2 | 1 | 1 | 0 | 1 |
| 2 | 3 | 1 | 0 | 0 | 1 |
| 3 | 3 | 1 | 0 | 1 | 1 |
| 4 | 3 | 1 | 0 | 1 | 1 |
| 2 | 4 | 0 | 1 | 1 | 1 |
| 3 | 4 | 1 | 0 | 0 | 1 |
| 4 | 4 | 0 | 0 | 1 | 0 |
+------------+--------+---+---+---+---+
最佳答案
试试这个
SELECT
a.*,
u.name,
q.*,
# (a.a & q.a) + (a.b & q.b) + (a.c & q.c) + (a.d & q.d) userCorrects,
# (a.a + a.b + a.c + a.d) questionCorrects,
((a.a & q.a) + (a.b & q.b) + (a.c & q.c) + (a.d & q.d)) / (a.a + a.b + a.c + a.d) as userGrade
FROM
answer a
INNER JOIN
user u ON a.userID = u.id
INNER JOIN
question q ON a.questionID = q.id
关于MySQL DB for exam (test quizzes) 查询分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43315610/