php - 使用 SQL 连接对大多数记录进行排序

标签 php sql mysql codeigniter sql-order-by

我下面有两个 MySQL 表

tophits
id, account, time

topsites
id, name, email, url

我的 topsites id 是 1(这是我的 tophits.account)。我想从 topsites 中选择名称和 url,并计算当天 account=1 的 tophits 中有多少条记录。

所以它们都会回显,哪个帐户点击次数最多将位于顶部等等

这是针对 codeigniter 的,我试过了..

$this->db->select('topsites.name, topsites.url, topsites.id, COUNT(tophits.account) as hit_count',FALSE);
   $this->db->from('topsites');
   $this->db->where('active', '0');
   $this->db->join('tophits', 'tophits.account = topsites.id', 'left');
   $this->db->like('tophits.time', '2011-01-25'); 
   $this->db->order_by('hit_count');
   $this->db->limit(10);

但是它只打印出一条记录,而且里面不止一条......有人知道这个问题吗?

最佳答案

您需要 GROUP BY 帐户(以显示多个帐户),并且还需要 ORDER BY "desc"以首先查看点击次数最多的帐户

$this->db->select('topsites.name, topsites.url, topsites.id, COUNT(tophits.account) as hit_count',FALSE);
$this->db->from('topsites');
$this->db->where('active', '0');
$this->db->join('tophits', 'tophits.account = topsites.id', 'left');
$this->db->like('tophits.time', '2011-01-25'); 
$this->db->group_by('topsites.name, topsites.url, topsites.id');
$this->db->order_by('hit_count', 'desc');
$this->db->limit(10);

关于php - 使用 SQL 连接对大多数记录进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4802384/

相关文章:

javascript - 哪些 MySQL 驱动程序可用于 node.js?

php - 查找参数并与其他表中的日期进行比较,按参数排序

php - 使用 Kohana 3 PHP 的 RESTful Web 服务

php - 了解嵌套的 PHP 三元运算符

javascript - php先执行完成,然后javascript运行

php - 如何获取最新数量的sql子查询

sql - 具有多个 JOINS 和 GROUP BY CLAUSE 的查询中的 COUNT

mysql - 为什么这个查询需要这么长时间才能执行

mysql - 是否可以根据创建日期安排从 mysql 表中删除行?

mysql - MySQL 中限制子级数量的约束