我试图将这个表中的每个答案与其问题的标题联系起来。我知道嵌套查询是一个坏主意。有没有另一种方法可以做到这一点?

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'
}

最佳答案

您可以进行自连接:

select questions.postid, questions.title, answers.postid, answers.title,
  from table as questions
 inner join table as answers on (questions.postid = answers.parent_postid);

关于php - 在同一个mysql表上组合多个查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6310977/

10-13 01:33