Php 使用表A中的id计算表B中的行
我一定很累了,因为我知道我以前做过这个,但我不记得我是怎么做的,也不记得找到了那个片段。我有两张表格“问题”和“答案”。“问题”中的主要“id”在“答案”中也是“id”。我试图根据表格中的“id”来计算“答案”Php 使用表A中的id计算表B中的行,php,mysql,count,Php,Mysql,Count,我一定很累了,因为我知道我以前做过这个,但我不记得我是怎么做的,也不记得找到了那个片段。我有两张表格“问题”和“答案”。“问题”中的主要“id”在“答案”中也是“id”。我试图根据表格中的“id”来计算“答案” <?php $query = "SELECT * FROM questions ORDER BY id DESC"; $result = mysql_query("$query"); while($row = mysql_fetch_array($resu
<?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 />");
}
?>
要获得每个问题的答案数,您可以这样做
select q.id,
count(*) as answers
from answer a
left join questions q on q.id = a.id
group by q.id
要获得每个问题的答案数,您可以这样做
select q.id,
count(*) as answers
from answer a
left join questions q on q.id = a.id
group by q.id
首先,您从未执行过$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.
首先,您从未执行过$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.
SELECT COUNT(answers.id)FROM questions LEFT JOIN answers ON questions.id=answers.id WHERE questions.id=$id
SELECT COUNT(answers.id)FROM questions LEFT JOIN questions.id=answers.id WHERE questions.id=$id
噢,好的悲伤。计数嘘。我知道我现在没钱了。谢谢你,伙计。哇!我正在解雇自己——就在我醒来之后。哦,天哪。计数嘘。我知道我现在没钱了。谢谢你,伙计。哇!我正在解雇自己——就在我醒来之后。