如何使用join 5表从数据库中获取数据

时间:2017-03-22 04:48:28

标签: php mysql join

示例数据

job_category
**catergory_id**      **category_name**
      3                   Tourism and Travel Services

job
**job_id**      **role**                   **category_id**
   1        Financial Accountant               3

exam_paper
**exam_paper_id** **exam_paper_name** **job_id**
    1                  FA -TTS             1

question
**question_id  question  option1 option2 option3 option4** 
    15          AAA         a1     a2      a3       a4
    38          BBB         b1     b2      b3       b4
    39          CCC         c1     c2      c3       c4
    44          DDD         d1     d2      d3       d4
    45          EEE         e1     e2      e3       e4

exam_question_list
**id**  **exam_paper_id** **category_id** **job_id**   **q1  q2  q3  q4  q5**
  1          1                    3         1            15  38  39  44   45 

我想从exam_question_list表中获取详细信息,预期结果是问题,问题表中的选项根据question_paper_list表'q1-q5'

我尝试获取数据,但它无效;

SELECT *
FROM exam_question_list eq
LEFT JOIN exam_paper ex
    ON eq.exam_paper_id = ex.exam_paper_id
LEFT JOIN job j
    ON j.job_id = ex.job_id
LEFT JOIN job_catergory jc
    ON jc.catergory_id = j.catergory_id
LEFT JOIN question q
    ON q.question_id=eq.q1

此查询仅提供问题1.我想得到所有5个问题。怎么做?

2 个答案:

答案 0 :(得分:0)

您的查询错误。正确是

SELECT eq.*
FROM exam_question_list eq 
LEFT JOIN exam_paper ex ON eq.exam_paper_id = ex.exam_paper_id
LEFT JOIN job j ON j.job_id = ex.job_id
LEFT JOIN job_catergory jc ON jc.catergory_id = j.catergory_id
LEFT JOIN question q ON q.question_id=eq.q1

答案 1 :(得分:0)

您需要有问题的外键,因为相关数据存在 然后你开始用问题选择所有加入你放在哪里= id_whherever_you_want

exam_question_list与任何事情都没有关联尝试制作一个关系数据模型,这有助于您了解您需要在数据库中进行哪些更改。 删除exam_question_list并将所有外键置于问题