0

我正在尝试制作测试答案的百分比。

我有 3 个表的 mysql 数据库

桌子tests

id | name
---+--------
1  | test 1
2  | test 2

questions带有测试问题的表格

id | name       | test_id
---+------------+--------
1  | question 1 | 1
2  | question 2 | 1
3  | question 3 | 1
4  | question 4 | 1
5  | question 1 | 2
6  | question 2 | 2
7  | question 3 | 2
8  | question 4 | 2

answers我在其中放置了所有测试答案的表格

id | question_id
---+-------------
1  | 1
2  | 2
3  | 5
4  | 6
5  | 7
6  | 8

如何在测试中获得包含已完成问题百分比的列表。在这种情况下:

name   | percentage
-------+-----------
test 1 | 50
test 2 | 100
4

1 回答 1

3

尝试

select t.name, 
       cast((count(a.id) / count(q.id)) * 100 as unsigned) as percentage
from tests t
left outer  join questions q on q.test_id = t.id
left outer  join answers a on a.question_id = q.id
group by t.name

请参阅此SQLFiddle示例

于 2012-07-02T12:09:04.267 回答