2011-06-10 48 views
4

我試圖將表中的每個答案與其問題的標題連接起來。我知道嵌套查詢是一個壞主意。有沒有另一種方法來做到這一點?在同一個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' 
} 

回答

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); 
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')"; 
0

你應該能夠剛剛加入該表的兩個副本一起鏈接的問題和答案。

SELECT q.title, 
      a.content 
FROM  table q 
JOIN  table a 
ON  a.parent_postid = q.postid 
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更改時,您都可以循環並開始處理新問題。