使用表A php mysql中的id计算表B中的行

时间:2012-10-08 23:31:41

标签: php mysql count

我必须筋疲力尽,因为我知道我以前做过这件事,但我不记得我是怎么做的,或者找不到那个片段。我有两个表“问题”和“答案”。来自“问题”的主要“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 />");
  }

  ?>

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

要获得每个问题的答案数,您可以执行此操作

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