使用不同的where子句加入2表

时间:2018-05-12 09:09:58

标签: php mysql pdo

我的数据库中有2个表

1的 admin_store_exam   列是    exam_name A_QNum math_ques,math_a,math_b,math_c,math_d,A_Ans

2的 student_ans_history   列是    EXAM_NAME S_ID S_QNum S_Ans S_Noans

现在,我想将 exam_name 列中的这两个表与不同的WHERE子句一起加入。

以下是WHERE Clause的两个不同查询。

$sql="SELECT * FROM admin_store_exam WHERE exam_name='$en'";

$sql="SELECT * FROM student_ans_history WHERE exam_name='$en' AND S_ID='$session_contact'";

加入这两张桌后,我得到了这些。

$sql="
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 
 WHERE admin_store_exam.exam_name = '$en' 
  JOIN student_ans_history 
 WHERE student_ans_history.exam_name = '$en' 
   AND S_ID = '$session_contact' 
    ON admin_store_exam.exam_name = student_ans_history.exam_name
 ";

但不幸的是我不会得到任何结果。 我对sql不是很熟悉,所以无法理解我在哪里做错了。任何人都可以帮我解决这个问题。感谢..

1 个答案:

答案 0 :(得分:0)

您可以像以下一样加入:

$sql="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
 , CONCAT(S_Ans,S_Noans) AS S_Ans
  FROM admin_store_exam 
 INNER 
  JOIN student_ans_history 
    ON admin_store_exam.exam_name = student_ans_history.exam_name 
        AND admin_store_exam.A_QNum = student_ans_history.S_QNum
 WHERE admin_store_exam.exam_name = '$en' 
   AND student_ans_history.S_ID = '$session_contact'
    GROUP BY admin_store_exam.exam_name, admin_store_exam.A_QNum";

希望这有效!!!