0

我有一个具有这种结构的表:

opinion_id、author_id、标题、内容

我想从表中获取所有最新记录,作者一条记录,这意味着每个作者的最新记录...

我的独特功能似乎不起作用......

 function getOpinions() {

     $data = array();
     $this->db->select('*');
     $this->db->from('opinions');
     $this->db->join('authors', 'opinions.author_id = authors.author_id');
     $this->db->order_by('date', 'desc');
     $this->db->distinct('author_id');

     $Q = $this->db->get();
     if ($Q->num_rows() > 0) {
         foreach($Q->result_array() as $row) {
             $data[] = $row;
         }
     }
     $Q->free_result();
     return $data;

 }
4

1 回答 1

3

在 Codeigniter 中,distinct 不会按照您对字段名称的期望方式工作。如果您查看手册-没有区别的论据。如果您查看代码,它只需要一个布尔值,默认为 true。它只是在DISTINCT关键字之后将关键字添加到查询中SELECT。而已。

在您的情况下,我认为最好使用GROUP BYas $this->db->group_by('opinions.author_id');

希望在这种情况下,通过在分组之前进行排序,order by 可以根据您的需要起作用。

干杯!

编辑- OP评论后更新

我知道排序可能会搞砸 - 我有点提到它:) 无论如何,我可能会在这里假设你的一些表结构,但这会迫使GROUP BY你选择顶部的行。我假设日期在opinions桌面上,您只想要最新的行以及作者详细信息。

SELECT * FROM `authors`
JOIN (
    SELECT * FROM opinions
    ORDER BY `date` DESC
) AS ops ON ops.author_id = authors.author_id
GROUP BY ops.author_id

但是,您将无法在活动记录上构建此查询。希望这可以帮助。

于 2013-08-29T02:08:54.430 回答