-4

i have below table where i m storing question and multiple answers with id of quetion as below

table
ID Content QID
1  Q1      0
2  Q2      0
3  A1      1
4  A1      2
5  A2      1
6  A2      2

in above example Q for Question and A for Answer

Now i need result as question then its answer and so on e.g

I need output like First question and then all answer of that question.. then second question and all answers of that question...

1 Q1
3 A1
5 A2
2 Q2
4 A1
6 A2
samirprogrammer
  • 438
  • 5
  • 18

2 Answers2

1

Here's one cheap solution (tested with MySQL):

SET @max_id = (SELECT MAX(ID) FROM `table`);
SELECT * FROM `table` ORDER BY IF(QID > 0, @max_id * QID + ID, @max_id * ID) 

It works only for one level of Questions/Answers. So if an answer can have sub-questions and sub-answers, this solution won't work for you. I'm sure there are better solutions.

If you want to run it in one query, you can do it like that:

SELECT * FROM `table`
ORDER BY IF(QID > 0,
  (SELECT MAX(ID) FROM `table`) * QID + ID,
  (SELECT MAX(ID) FROM `table`) * ID) 
vstm
  • 12,407
  • 1
  • 51
  • 47
  • Thanks.. but when i test it is showing as Q1,Q2,A1,A2.. i need question then all answer and then next question and all answer of it – samirprogrammer Nov 29 '12 at 08:43
  • Maybe it's because of the @max_id variable. I have now added a second query, could you try that? – vstm Nov 29 '12 at 08:52
  • Yes but still same answer is in proper order but both question coming first..e.g. Q1,Q2... – samirprogrammer Nov 29 '12 at 08:57
  • Well I've tested it with your sample data and it worked. So I guess you're doing it with your real data. You probably have to modify the expression `QID > 0` - if your questions have a QID of 1 (in your sample they have 0) you have to write `QID > 1`. – vstm Nov 29 '12 at 09:02
  • Thanks a lot it is wroking... – samirprogrammer Nov 29 '12 at 09:08
1

First of all, I realy think this is a bad way of storing your data. Second, I even think it is a bad way of retrieving your data...

Anyway, I did not find a SQL statement for your result yet, but maybe this can help you:

SELECT question.ID as QuestionID, question.Content as Question, 
answer.ID as AnswerID, answer.Content as Answer 
FROM Test question, Test answer 
WHERE question.ID = answer.QID 
ORDER BY question.Content ASC

This should allow you to do what you want with the results... (Tested with SQL Server)

Frederik Prijck
  • 1,424
  • 10
  • 16