1

now my joined table returns the first posts row, i want it to have the last row for each topic

this is my code now

$this->db->select('*');
      ->where('disccategory_id', $cat);
       ->from('discussiontopics as topics');
       ->join('discussionposts as posts', 'posts.topic_id = topics.id', 'left');
       ->order_by('posts.id', 'desc');
       ->group_by('topics.id');

maybe i can only do it with a select inside the join? but not sure how to do that with Codeigniter's Active Record

4

2 回答 2

2
$this->db->query("
SELECT *
FROM (  SELECT *,
            topics.id AS topic_id
        FROM discussiontopics as topics
        LEFT JOIN discussionposts as posts
        ON posts.topic_id = topics.id
        ORDER BY posts.id DESC) AS h
GROUP BY topic_id
");

如果你想知道为什么你的不工作,运行一个运行echo $this->db->last_query();后的查询,你会看到 if 的行为。

于 2012-12-13T15:38:57.413 回答
0

实际上它应该不起作用,原因是分组ORDER BY执行,如果你写

->order_by(...)
->group_by(...)

或者

->group_by(...)
->order_by(...)

没关系,查询总会有GROUP BYbefore ORDER BY

您最有可能遇到的问题在这里讨论:

分组前的 MySQL 顺序

所以我宁愿使用手动编写查询

$this->db->query('
    SELECT ...
');

或者甚至获取行列表(您的查询没有分组)并且只取第一个。

希望能帮助到你!

于 2012-12-13T13:25:36.830 回答