【问题标题】:CakePHP paginate causing weird DISTINCT behaviorCakePHP 分页导致奇怪的 DISTINCT 行为
【发布时间】:2014-07-03 00:26:10
【问题描述】:

我有一个非常基本的分页查询,在我将 DISTINCT 放在其中一列上之前它工作正常。

以下作品:

$this->paginate = array(
    'conditions' => array(Message.recipient_id' => $this->Auth->user('id')),
    'fields' => array(
        'DISTINCT Message.sender_id',
        'Message.recipient_id',
        'Message.thread_id',
    ),
    'limit' => 15,
    'order' => array('Message.created' => 'DESC')
);

这个查询不起作用:

$this->paginate = array(
    'conditions' => array(Message.recipient_id' => $this->Auth->user('id')),
    'fields' => array(
        'DISTINCT Message.sender_id',
        'Message.recipient_id',
        'Message.thread_id',
        // If I add any of the following columns, the DISTINCT doesn't work at all
        'Message.created',
        'Message.modified',
        'Message.id'
    ),
    'limit' => 15,
    'order' => array('Message.created' => 'DESC')
);

为什么 'fields' 选项中的任何其他列会与 DISTINCT 关键字发生冲突?

这对我来说没有任何意义。

【问题讨论】:

    标签: php mysql cakephp pagination


    【解决方案1】:

    如果您的意思是“它不起作用”,尽管存在不同的列,但您会收到具有相同 sender_id 的多条消息......那么原因是因为当使用带有 distinct 关键字的多个列时,它会查找所有列的唯一组合。 Message.created、Message.modified 和 Message.id 在大多数或所有情况下每行都是唯一的,因此这些列本身将使您的字段组合不同​​。尝试使用 Message.sender_id 分组。

    $this->paginate = array(
        'conditions' => array(Message.recipient_id' => $this->Auth->user('id')),
        'fields' => array(
            'Message.sender_id',
            'Message.recipient_id',
            'Message.thread_id',
            'Message.created',
            'Message.modified',
            'Message.id'
        ),
        'limit' => 15,
        'order' => array('Message.created' => 'DESC'),
        'group' => array('Message.sender_id'),
    );
    

    【讨论】:

    • 我一开始确实使用了“组”,但后来“订单”被忽略了。但至少现在我明白了为什么 DISTINCT 在这种情况下不起作用。是否可以仅将 DISTINCT 关键字应用于一列以便它起作用?或者有其他解决方案吗?这很令人沮丧。
    • 据我所知,如果你在mysql查询中使用group by x order by x,它会被排序。也许 cakePHP 正在生成的查询不包括 order by。因此,您应该检查它正在创建的实际查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    相关资源
    最近更新 更多