【发布时间】:2012-07-22 02:54:59
【问题描述】:
您好,我的问题是我只想获取“last_...”的最后一个主题。一个简单的 order_by 将不起作用,因为它也会对论坛进行排序,这是我不想要的。我到目前为止的代码。我在 CodeIgniter 的内置 Active Records 中执行此操作。
return $this->db->select('forums.*,')
->select('Count(topics.id) threads, Count(replies.id) replies')
->select('topics.url last_post_url, topics.name last_post_name, topics.created last_post_date')
->select('users.url user_url, users.name user_name, ranks.name user_rank')
->from('forums')
->join('topics', 'topics.f_id = forums.id', 'left')
->join('replies', 'replies.t_id = topics.id', 'left')
->join('users', 'users.id = topics.a_id', 'left')
->join('ranks', 'users.status = ranks.id','left')
->group_by('forums.id')
->get()
->result();
如果不清楚我要做什么; 我希望它获得论坛,我希望它在每一行中添加数量或主题(工作)、回复数量(工作)以及最后发帖的人。
原始查询
SELECT `forums`.*, Count(topics.id) threads, Count(replies.id) replies, `users`.`url` user_url, `users`.`name` user_name, `ranks`.`name` user_rank
FROM (`forums`)
LEFT JOIN `topics` ON `topics`.`f_id` = `forums`.`id`
LEFT JOIN `replies` ON `replies`.`t_id` = `topics`.`id`
LEFT JOIN `users` ON `users`.`id` = `topics`.`a_id`
LEFT JOIN `ranks` ON `users`.`status` = `ranks`.`id`
GROUP BY `forums`.`id`
【问题讨论】:
-
你能提供sqlfiddle.com上的表结构吗
-
遗憾的是,我尝试将 sql 导出到其中,但我只是在错误处理后出现错误,几乎没有错误处理。 pastebin.com/emA55BdY 那里有它的粘贴,但如果你能让它工作的话。我的两个问题是last_post_url、last_post_name 和last_post_date 必须是最新的话题或回复(取决于哪个是后者)。
-
我尝试重新创建您的架构并向其中添加一些测试数据,see if it fits 并编辑问题。另外,我认为您正在考虑关于“The Rows Holding the Group-wise Maximum of a Certain Column”的问题。
-
complex857,你遇到了和我一样的问题,它获取的是第一个主题,而不是最后一个。在您的情况下,它获取创建“2012-07-24 14:54:21”的“topic1”,而创建“2012-07-28 00:00:00”的 topic3。它还应该检查回复和主题。 Topic1 创建于 14:30:30,Topic2 创建于 13:45:45,Reply1 创建于 13:50:50,那么它应该获取 reply1。提前致谢。还要感谢子查询,我会尝试一下,但不确定 codeigniter 是否支持它,但必须以“老式”方式进行!
-
是的,它不是一个解决方案,它是在一个对实验更友好的环境中复制您的代码以添加到您的问题中,因此其他人可能会更好地理解它。但是由于我无法验证我是否正确地重新创建了您的内容,因此我没有将其作为编辑提交。
标签: php mysql codeigniter join sql-order-by