简体   繁体   中英

Get data from two tables?

I have 2 tables.

One holds questions:

id | question
1   How old are you?
2   Are you male of female?

The other holds exams:

id  |   title     |  question_ids
1    Summer Exam     [1,2]

My question is, I want to select an exam from the exams table, and get all of the questions related to that particular exam (the question_ids field), but get the question from the question table and not just the id stored in question_ids.

How can I do this?

You can use the FIND_IN_SET command. Note that this will NOT use your indexes, so it may be pretty slow

SELECT title, question
FROM questions
INNER JOIN exams
ON FIND_IN_SET(questions.id, exams.question_ids)

You could also use an IN . Note that this will only work when selecting a specific exam. Without selecting a specific exam you will return every record referenced in the question_ids column in the entire exams table

SELECT title, question
FROM questions, exams
WHERE exams.id = 1
AND questions.id IN (question_ids)

Maybe change your id column in your question table to be q_id and question_id to also be called q_id so you have a clear way to link your tables. Change your id column to be called exam_id for instance and then your names are less confusing. Then you can use an inner join for instance...

SELECT q.q_id, q.question, e.exam 
FROM questions q 
 INNER JOIN exams e ON q.q_id=e.q_id 
WHERE ......

Something like that.

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