简体   繁体   English

Codeigniter选择不同的功能不起作用

[英]codeigniter select distinct function not working

I have a table with this structure: 我有一个具有这种结构的表:

opinion_id, author_id, title, content 意见编号,作者编号,标题,内容

I would like to get all the latest records from the table, one record for author, that means the latest record for every author... 我想从表中获取所有最新记录,一个给作者的记录,这意味着每个作者的最新记录...

My distinct function does not seem to be working... 我独特的功能似乎无法正常工作...

 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;

 }

In Codeigniter, distinct does not work the way you expect it by field name. 在Codeigniter中,distinc不能按您期望的字段名称那样工作。 If you look at the manual - there is no argument for distinct. 如果您查看该手册 ,则没有论点。 If you look at the code, it only takes a boolean, which defaults to true. 如果您查看代码,则只需要一个布尔值,默认为true。 It just adds the DISTINCT keyword to the query after the SELECT keyword. 它只是将DISTINCT关键字添加到查询中SELECT关键字之后。 That's it. 而已。

In your case, I think it would be better to use a GROUP BY as in $this->db->group_by('opinions.author_id'); 在您的情况下,我认为最好使用GROUP BY$this->db->group_by('opinions.author_id');

Hopefully the order by would work as per your need in this instance by ordering before the grouping. 希望在这种情况下可以通过在分组之前进行订购来按您的需要进行订购。

Cheers! 干杯!

EDIT - update after OP comments 编辑 -OP评论后更新

I know the ordering can be messed up - I sort of mentioned it :) Anyway, I might be assuming some of your table structure here, but this would force the GROUP BY to pick the rows on the top. 我知道排序可能会搞乱-我有点提到它了:)无论如何,我可能在这里假设您的某些表结构,但这将迫使GROUP BY选择顶部的行。 I assume that the date is on the opinions table and you only want the latest row from that with author details. 我认为日期在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

You will not be able to construct this query on active record though. 但是,您将无法在活动记录上构造此查询。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM