用不同的where子句连接2表

m0rkklqb  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(325)

我的数据库中有2个表
1.admin\u store\u考试列包括考试名称、a\u qnum、数学问题、数学a、数学b、数学c、数学d、a\u ans
2.学生历史栏包括考试名称、学号、学号、学名、学名
现在我想用不同的where子句连接exam\u name列上的这两个表。
下面是两个不同的where子句查询。

$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不是很熟悉,所以不明白我在哪里犯了错。有人能帮我解决这个问题吗。谢谢。。

iecba09b

iecba09b1#

可以使用子查询。考虑以下示例:

SELECT A.* FROM
(SELECT * FROM admin_store_exam WHERE exam_name='AB') AS A
INNER JOIN
(SELECT * FROM student_ans_history WHERE exam_name='AB' AND S_ID='23344') AS B
ON A.exam_name = B.exam_name
a14dhokn

a14dhokn2#

您可以像这样加入:

$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";

希望这个工作!!!

相关问题