2012-10-08 88 views
1

我必須精疲力竭,因爲我知道我以前做過這件事,但我不記得我是如何做的,或者是否找到該代碼段。我有兩個表格「問題」和「答案」。 「questions」中的主要「id」在「答案」中也是「id」。我試圖根據該表中的「id」來計算「答案」。從表B中使用ID從表A中計數行php mysql

 <?php 

    $query = "SELECT * FROM questions ORDER BY id DESC"; 

    $result = mysql_query("$query"); 
    while($row = mysql_fetch_array($result)){ 
$id = $row['id']; 
    $date = $row['date']; 
    $question = $row['question']; 
$time = date("U"); 
$likes = $row['likes']; 
    $query2 = "SELECT * FROM answers WHERE id = $id"; 
    $num_rows = mysql_num_rows($query2); 
    print("<span style='font-size: .7em';><a href='qplusone.php?id=$id'>+1</a> 
- Likes:$likes</span> $question - <a href='answer.php?id=$id&pp=$time'>answer it</a> 
or <a href='answers.php?id=$id&pp=$time'>read $num_rows answers</a> 
<span style='font-size: .7em';>($date)</span><br />"); 
    } 

    ?> 
+0

'SELECT COUNT(answers.id)FROM問題LEFT JOIN答案ON questions.id = answers.id WHERE questions.id = $ id' –

回答

1

嗯,首先,你永遠不執行$query2的。但是,要比返回所有行並對它們進行計數更好,只需返回mysql計算的行數即可。

$query2 = "SELECT count(*) FROM answers WHERE id = $id"; 
$result = mysql_query($q); 
$row = mysql_fetch_array($result); 

$count = $row['count(*)']; // $count holds the number of matching records. 
+0

哦,好傷心。計數。嘖。我知道我現在已經不在了。謝啦。哇。我正在解僱自己 - 在我醒來之後。 – mrmunk

0

要獲得每個問題的答案的數量,你可以做到這一點

select q.id, 
     count(*) as answers 
from answer a 
left join questions q on q.id = a.id 
group by q.id 
相關問題