Mysql - merge the same table data

I have a table where all comments are stored. Some comments are questions, others are answers. So my table looks like this:

id  parent_id   message is_answer   answered
1   0           2x2     0           1
2   1           4       1           0
3   0           5x9     0           0
4   1           2x9     0           0
5   1           2x8     0           1
6   5           16      1           0

And as a result, I would like to get this table:

q_id    q_message   q_answer 
1       2x2         4
3       5x9         NULL 
4       2x9         NULL
5       2x8         16

So, I would like to get all the questions and answers to them, if they exist.

+3
source share
2 answers

Nothing prevents you from joining a table for yourself.

SELECT q.id AS q_id, q.message AS q_message, a.message AS q_answer
FROM table AS q
LEFT JOIN table AS a ON a.parent_id = q.id
WHERE q.is_answer = 0;

Please note that this does not quite give the result you said you want ... because it displays all the answers to the question:

+------+-----------+----------+
| q_id | q_message | q_answer |
+------+-----------+----------+
|    1 | 2x2       | 4        | 
|    1 | 2x2       | 2x9      | 
|    1 | 2x2       | 2x8      | 
|    3 | 5x9       | NULL     | 
|    4 | 2x9       | NULL     | 
|    5 | 2x8       | 16       | 
+------+-----------+----------+
6 rows in set (0.00 sec)

"4" 1. , - , GROUP BY , .

+5

, :

select   q.id as q_id,q.message as q_message ,a.message as q_answer   FROM comments q LEFT OUTER JOIN comments a ON (a.parent_id = q.id and a.is_answer=1 and q.is_answer=0)

, is_answer, parent_id = NULL, ?

+2

All Articles