Php 在同一个mysql表上组合多个查询
我试着把这个表中的每个答案和它的问题的标题联系起来。我知道嵌套查询是个坏主意。还有别的办法吗Php 在同一个mysql表上组合多个查询,php,mysql,Php,Mysql,我试着把这个表中的每个答案和它的问题的标题联系起来。我知道嵌套查询是个坏主意。还有别的办法吗 postid | type | parent_postid | title | content ---------------------------------------------------- 1 | question | NULL | car wheels | how many 2 | answer | 1
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);
在运行此查询之前,您希望运行检查以确保数组中有ID,否则将出现错误
您还可以执行以下操作:
$query = "SELECT title FROM table WHERE postid IN (SELECT parent_postid FROM table WHERE type = 'answer')";
您应该能够将表格的两个副本连接在一起,以链接问题和答案
SELECT q.title,
a.content
FROM table q
JOIN table a
ON a.parent_postid = q.postid
注意,您必须为这些列添加别名,否则它们将具有相同的名称,并且无法按列名进行区分
您还需要使用orderby,以便将所有答案与相关问题组合在一起。每次questionID
更改时,您都可以循环并开始处理新问题
SELECT q.title,
a.content
FROM table q
JOIN table a
ON a.parent_postid = q.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