You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL关联两张表用不同WHERE子句无结果,请求语句纠错

解决两张表关联查询无结果的问题

我来帮你排查下这个SQL的问题哈!你的查询语句主要是语法顺序错误导致无结果返回,我一步步给你修正和解释:

核心错误点分析

  • JOIN子句的位置完全错了:SQL语法要求JOIN必须放在WHERE子句之前,而且关联条件ON要紧跟在被关联的表后面,不能甩到WHERE之后
  • 重复设置关联条件:你已经通过ON admin_store_exam.exam_name = student_ans_history.exam_name关联了两张表的考试名称,没必要在WHERE里再分别写两边的exam_name判断

修正后的SQL语句

版本1:INNER JOIN(仅返回学生有作答记录的题目)

如果只需要显示该学生在这场考试中提交过答案的题目,用INNER JOIN:

SELECT 
    admin_store_exam.A_QNum,
    admin_store_exam.math_ques,
    admin_store_exam.math_a,
    admin_store_exam.math_b,
    admin_store_exam.math_c,
    admin_store_exam.math_d,
    admin_store_exam.A_Ans,
    student_ans_history.S_Ans,
    student_ans_history.S_Noans
FROM admin_store_exam
JOIN student_ans_history 
    ON admin_store_exam.exam_name = student_ans_history.exam_name
WHERE 
    admin_store_exam.exam_name = '$en'
    AND student_ans_history.S_ID = '$session_contact'

版本2:LEFT JOIN(返回所有题目,含学生未作答的)

如果你希望看到这场考试的所有题目,哪怕学生没答过(未作答的S_Ans/S_Noans会显示NULL),建议用LEFT JOIN:

SELECT 
    admin_store_exam.A_QNum,
    admin_store_exam.math_ques,
    admin_store_exam.math_a,
    admin_store_exam.math_b,
    admin_store_exam.math_c,
    admin_store_exam.math_d,
    admin_store_exam.A_Ans,
    student_ans_history.S_Ans,
    student_ans_history.S_Noans
FROM admin_store_exam
LEFT JOIN student_ans_history 
    ON admin_store_exam.exam_name = student_ans_history.exam_name
    AND student_ans_history.S_ID = '$session_contact'
WHERE 
    admin_store_exam.exam_name = '$en'

重要提醒:避免SQL注入风险

你现在直接把$en和$session_contact拼接到SQL里,存在严重的SQL注入漏洞!建议改用预处理语句(以PHP为例):

// 使用mysqli预处理语句
$stmt = $conn->prepare("
    SELECT 
        admin_store_exam.A_QNum,
        admin_store_exam.math_ques,
        admin_store_exam.math_a,
        admin_store_exam.math_b,
        admin_store_exam.math_c,
        admin_store_exam.math_d,
        admin_store_exam.A_Ans,
        student_ans_history.S_Ans,
        student_ans_history.S_Noans
    FROM admin_store_exam
    LEFT JOIN student_ans_history 
        ON admin_store_exam.exam_name = student_ans_history.exam_name
        AND student_ans_history.S_ID = ?
    WHERE 
        admin_store_exam.exam_name = ?
");
$stmt->bind_param("ss", $session_contact, $en);
$stmt->execute();
$result = $stmt->get_result();

这样既安全,还能避免变量包含特殊字符导致的语法错误。

内容的提问来源于stack exchange,提问作者Sohon Shome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:29:36