解决方案:
$query = $this->db->query("
SELECT *, SUM(views.times) AS sum
FROM channel
RIGHT JOIN video
ON channel.channel_id = video.channel_id
LEFT JOIN user
ON channel.user_id = user.user_id
LEFT JOIN views
ON channel.channel_id = views.channel_id
GROUP BY channel.channel_name
ORDER BY sum DESC
");
我有一个返回项目列表的查询。
function getfrontpage(){
$this->db->select('*');
$this->db->from('channel');
$this->db->join('video', 'channel.channel_id = video.channel_id' , 'right');
$this->db->join('user', 'channel.user_id = user.user_id');
$this->db->group_by("channel.channel_name");
$query = $this->db->get();
return $query->result();
}
现在我正在尝试使用另一个表中的SUM来订购这些,我该如何实现?
以下是该表中的图片:
我希望结果按每个“channel_id”的“时间”总和的SUM进行排序
提前致谢
答案 0 :(得分:2)
我建议改为通过$this->db->query()
运行。
通过CodeIgniters AR函数获取简单值非常好。但在某些情况下,更容易构建查询字符串。
在你的情况下:
$query = $this->db->query("
SELECT channel_id, SUM(times) AS sum
FROM channel
GROUP BY channel_id
ORDER BY sum DESC
");
您还可以通过db-> query()!
转义大多数值$this->db->query("
SELECT name
FROM table_name
WHERE id = ?
", array(1));
答案 1 :(得分:1)
这不像$this->db->order_by("channel_id", "desc");
那么简单吗?这会按channel_id按降序对结果进行排序。
答案 2 :(得分:1)
假设您的问题中显示的表名为times_table,并且密钥为user_id,channel_id,您可以使用以下代码将times_table加入查询中,以便“times”列可用于排序。
$this->db->join("times_table", "times.user_id=channel.user_id, times.channel_id=channel.channel_id", "left");
// You've already grouped by channel_name, so grouping by channel_id is probably not necessary.
$this->db->order_by("SUM(times_table.times) DESC");
N.B。我猜对象显示的表名是times_table。