I have tables that look like this:
questions:
id description
1 Q1
2 Q2
answers:
id question_id x y description
1 1 1 2 A1
2 1 3 4 A2
3 2 5 6 A3
4 2 7 8 A4
What I want to get is a query that can output this:
Q1 A1 1,2 A2 3,4
Q2 A3 5,6 A4 7,8
I’ve been pulling my hair for days now trying to figure this out. I’m doing this in PHP and MySQL so if anyone can shed some light out there, that’d be really great.
EDIT: I forgot to mention that I’m using CodeIgniter for this, too. So, that might help with the answers.
Considering that there might be a random number of answers per question, you cannot design a query that will return a fixed number of columns. You have to return a single result per question and then do a little bit of parsing in your code.
The
GROUP_CONCATfunction can be helpful for this kind of problem:Will return
You can change the
SEPARATORvalue by whatever you want to parse the result in your code. You can use theORDER BYclause of theGROUP_CONCATfunction to order the answers in the returned result for each answer (here I ordered by answer id).Edit: If you are sure that there will never be more than 4 answers per question, you can issue the following query to put each answer in its own column:
Will return
I added an answer to the second question for the illustration.