Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine multiple queries on same mysql table

Tags:

php

mysql

I'm trying to connect each answer in this table with the title to its question. I understand that nested queries are a bad idea. Is there another way to do this?

postid | type     | parent_postid | title       | content
----------------------------------------------------
1      | question | NULL          | car wheels  | how many
2      | answer   | 1             | NUll        | 4 wheels

SELECT * FROM table WHERE type = 'answer'

while($row = mysql_fetch_array($result)) {
    $parent_postid = row['parent_postid'];
    SELECT title FROM table WHERE postid = '$parent_postid'
}
like image 218
Marcus Avatar asked Jan 20 '23 12:01

Marcus


1 Answers

You can do a self join:

select questions.postid, questions.title, answers.postid, answers.title,
  from table as questions
 inner join table as answers on (questions.postid = answers.parent_postid);
like image 139
Pablo Santa Cruz Avatar answered Jan 30 '23 07:01

Pablo Santa Cruz