在同一个mysql表上组合多个查询

时间:2011-06-10 19:07:10

标签: php mysql

我正在尝试将此表中的每个答案与其问题的标题相关联。我知道嵌套查询是个坏主意。还有另一种方法吗?

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

4 个答案:

答案 0 :(得分:8)

你可以自我加入:

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

答案 1 :(得分:1)

select question.postid as questionID, 
        question.title as questionTitle,
        question.content as questionContent,
        answer.content as answerContent
    from table question
        inner join table answer on(
            question.postid=answer.parent_postid
        )
    order by question.postid

请注意,您必须为列添加别名,因为它们将具有相同的名称,您将无法按列名进行区分。

您还希望使用orderby,以便将所有答案与相关问题分组。每次questionID更改时,您都可以循环并开始处理新问题。

答案 2 :(得分:0)

SELECT * FROM table WHERE type = 'answer'

$ids = array();
while($row = mysql_fetch_array($result)) {
    $ids[] = $row['parent_postid'];
}

$query = "SELECT title FROM table WHERE postid IN (".implode(',',$ids).")";

您希望在运行此查询之前运行检查以确保数组中有ID,否则您将收到错误。

你也可以做:

$query = "SELECT title FROM table WHERE postid IN (SELECT parent_postid FROM table WHERE type = 'answer')";

答案 3 :(得分:0)

您应该能够将表的两个副本连接在一起以链接问题和答案。

SELECT    q.title,
          a.content
FROM      table q
JOIN      table a
ON        a.parent_postid = q.postid