简体   繁体   中英

How to get data from database using join 5 tables

Sample data

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 

I want to get the details from the exam_question_list table, the expected results are the question, options from the question table according to the question_paper_list table 'q1-q5'

I try to get data, but it is not working;

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

this query give only question 1 only.I want to get All 5 questions.How to do it?

Your Query is wrong. Correct is

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

you need the foreign keys in question because the relevant data is there and you start you select with question after all join you put where = id_whherever_you_want

the exam_question_list isn't associated with anything try make one relational data model this help you understand what u need change in database. delete exam_question_list and put all foreign keys on question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM