MySql如何从一个表中选择所有问题及其答案

时间:2013-04-22 09:13:18

标签: mysql

我的表格结构是:(我支持q代表问题,答案只是描述它是什么,id和parent_id都是INT类型,id是auto_increment)

id title parent_id 
q1 ****  0( 0 means it was a question)
a2 ****  q1
a3 ****  q1
q4 ****  0
q5 ****  0
a6 ****  q4
a7 ****  q1
...

在管理页面,我希望他们在问题中列出,然后是Answers.Just就像:

Qustion1:****
Answer2: ****
Answer3: ****
Answer7: ****

Question4:****
Answer6: ****

Question5:****
Answer:none

任何建议都将非常感谢:)

2 个答案:

答案 0 :(得分:3)

可能是最简单的答案:

SELECT * from qa
ORDER BY case parent_id when 0 then id else parent_id end, id

SQLFiddle here

答案 1 :(得分:1)

SELECT 
    * 
FROM 
    (
        (SELECT 
            *
         FROM qa AS q
         WHERE q.parent_id = 0
         ORDER BY q.id 
         )
UNION ALL 
        (SELECT 
            *
         FROM qa AS q
         WHERE q.parent_id <> 0
         ORDER BY a.id)
) AS r
ORDER BY id , parent_id

See SQL Fiddle Demo Here

输出

| ID | TITLE | PARENT_ID |
--------------------------
|  1 |    Q1 |         0 |
|  2 |    A1 |         1 |
|  3 |    A2 |         1 |
|  4 |    A3 |         1 |
|  5 |    A4 |         1 |
|  6 |    Q2 |         0 |
|  7 |    A1 |         6 |
|  8 |    A2 |         6 |
|  9 |    A3 |         6 |
| 10 |    A4 |         6 |
| 11 |    Q3 |         0 |
| 12 |    A1 |        11 |
| 13 |    A2 |        11 |
| 14 |    A3 |        11 |
| 15 |    A4 |        11 |

已编辑:

您也可以使用带有IF条件的Mark Ba​​nnister答案

SELECT 
    * 
from qa
ORDER BY IF(parent_id = 0 ,id ,parent_id ) , id