SQL查询错误排查:统计用户匹配正确答案的答题数量
SQL语句错误分析
数据表信息
Table1
| ID | Name |
|---|---|
| 1 | Brie |
| 2 | Ray |
| 3 | James |
Table2
| ID | Q_id | Q_no | ans |
|---|---|---|---|
| 1 | 2304. | 1 | A |
| 1 | 2304. | 2 | A |
| 1 | 2305. | 1 | C |
| 2 | 2304. | 2 | A |
| 2 | 2305. | 1 | C |
| 3 | 2304. | 1 | A |
| 3 | 2305. | 2 | D |
Table3
| Q_id | Q_no | correct_ans |
|---|---|---|
| 2304. | 1 | A |
| 2304. | 2 | B |
| 2305. | 1 | C |
| 2305. | 2 | D |
需求
输出包含ID、姓名以及Table2中答案与Table3正确答案匹配的条目数的表格,预期结果:
| ID | Name | ans_count |
|---|---|---|
| 1 | Brie | 2 |
| 2 | Ray | 1 |
| 3 | James | 2 |
你的SQL语句
Select t1.ID, Name, count(t2.ans) as ans_count from Table1 t1 join Table2 t2 on t1.ID=t2.ID join Table3 t3 on t2.Q_id=t3.Q_id where t2.ans=t3.correct.ans and t2.q_no=t3.q_no group by t1.ID order by t1.ID
错误点分析
- 字段名拼写错误:
t3.correct.ans是错误写法,Table3中正确答案的字段名是correct_ans,不存在.分隔的结构,应改为t3.correct_ans。 - 连接条件逻辑不严谨:你把
t2.q_no = t3.q_no放在where子句中,应该将其移到Table3的连接条件里,这样能提前过滤不匹配的记录,避免产生不必要的临时数据,逻辑也更清晰。 - 分组字段不完整:多数SQL方言(如MySQL 5.7+、PostgreSQL、SQL Server)要求
group by子句包含所有非聚合的查询字段。你查询了t1.ID和Name,但仅分组t1.ID,若Name与t1.ID并非严格一一对应会报错,建议改为group by t1.ID, t1.Name。
修正后的SQL语句
SELECT t1.ID, t1.Name, COUNT(t2.ans) AS ans_count FROM Table1 t1 JOIN Table2 t2 ON t1.ID = t2.ID JOIN Table3 t3 ON t2.Q_id = t3.Q_id AND t2.Q_no = t3.Q_no WHERE t2.ans = t3.correct_ans GROUP BY t1.ID, t1.Name ORDER BY t1.ID
内容的提问来源于stack exchange,提问作者Animate It
相关产品推荐
相关产品推荐

