我必须将sql table1表示为question而table2表示注释
我希望帖子的评论数量最多
如何在两个表之间进行此操作?
像这样的表格问题id title
----- -------
1 title1
2 title2
3 title3
4 title4
像这样的表评论
id content questid
----- ------- --------
1 test 1
2 test 3
2 test 3
2 test 3
我的代码
$gquest = $DB_con->prepare("SELECT * FROM `question` ORDER BY id DESC");
$gquest->execute();
foreach ($gquest->fetchAll() as $rowL)
{
$cat = $DB_con->prepare("SELECT * FROM `comment` WHERE `questid`=".$rowL['id']."");
$cat->execute();
$cominf = $cat->fetch(PDO::FETCH_ASSOC);
$countquest = $cat->rowCount();
$gqt = $DB_con->prepare("SELECT * FROM `question` ORDER BY ".$cominf['id']." DESC");
$gqt->execute();
$cfr = $gqt->fetch(PDO::FETCH_ASSOC);
}
答案 0 :(得分:3)
您可以通过加入问题ID上的两个表,然后COUNT()
每个问题的评论出现次数,从单个查询中获取您要查找的内容。以下是它的外观示例:
$gquest = $DB_con->prepare("
SELECT q.*, COUNT(c.questid) AS num_comments
FROM question q
JOIN comment c
ON q.id = c.questid
GROUP BY q.id
ORDER BY num_comments DESC
LIMIT 1;
");