Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用于聚合相关对象的SQL查询_Php_Mysql_One To One - Fatal编程技术网

Php 用于聚合相关对象的SQL查询

Php 用于聚合相关对象的SQL查询,php,mysql,one-to-one,Php,Mysql,One To One,我有两个表作为帖子和评论。comments表中的每一行都有它所属的帖子的id。例如,如何选择评论最多的十篇文章?试试这个 SELECT p.id, COUNT(c.id) tot FROM posts p INNER JOIN comments c ON p.id = c.post_id GROUP BY p.id ORDER BY tot DESC LIMIT 10 您可以使用分组方式进行此操作 有些疑问像 SELECT posts, count(comment) as total fr

我有两个表作为帖子和评论。comments表中的每一行都有它所属的帖子的id。例如,如何选择评论最多的十篇文章?

试试这个

SELECT p.id, COUNT(c.id) tot
FROM posts p INNER JOIN comments c
ON p.id = c.post_id
GROUP BY p.id
ORDER BY tot DESC
LIMIT 10 

您可以使用分组方式进行此操作 有些疑问像

SELECT posts, count(comment) as total 
from comments group by (post) order by total;

这个问题很简单。你试过什么吗?不要要求为您编写代码,这是非常基本的SQL。我认为您缺少表之间的关系,您选择的是注释,而不是大多数注释文章。最后你没能进入前十名。@diEcho:哦,我的错。。。我度过了糟糕的一天,我没有注意到这一点。。。是的,你完全正确,
LIMIT
走到了尽头!!谢谢