1

我一定筋疲力尽,因为我知道我以前做过,但我不记得我是怎么做的或找到那个片段的。我有两个表“问题”和“答案”。“问题”中的主要“id”也是“答案”中的“id”。我正在尝试根据该表中的“id”计算“答案”。

     <?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 />");
  }

  ?>
4

2 回答 2

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.
于 2012-10-08T23:36:34.013 回答
0

要获得每个问题的答案计数,您可以这样做

select q.id,
       count(*) as answers
from answer a
left join questions q on q.id = a.id 
group by q.id
于 2012-10-08T23:34:04.430 回答