简体   繁体   English

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

[英]combine multiple queries on same mysql table

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

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);
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

Note you have to alias the columns since they'll otherwise have the same name and you wouldn't be able to differentiate by column name.请注意,您必须为列起别名,否则它们将具有相同的名称,并且您将无法按列名进行区分。

You also want to use the orderby so you can group all the answers together with the relevant question.您还想使用 orderby,以便将所有答案与相关问题组合在一起。 You can loop through and start processing a new question everytime the questionID changes.每次questionID更改时,您都可以循环并开始处理新问题。

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).")";

You want to run a check to make sure you have ids in your array before you run this query or you will get an error.您想在运行此查询之前运行检查以确保您的数组中有 id,否则您将收到错误消息。

You could also do a:您还可以执行以下操作:

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

You should be able to just join two copies of the table together to link the questions and answers.您应该能够将表格的两个副本连接在一起以链接问题和答案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM