我接受了答案。但欢迎提出更多答案和建议。
我变得与众不同 - 在CakePHP查询中使用distinct时,MySQL结果不同。
我要做的是: date_generated 字段的不同结果。
问题:查询1工作正常,但是当我收到两个字段(date_generated,id)(请参阅查询2)时,不同结果无效。
查询1
$this->Purchase->find('all',array(
'order' => array('Purchase.date_generated ASC'),
'fields' => array('DISTINCT Purchase.date_generated')));
查询1的结果:在此结果中 date_generated 不重复且工作正常。请查看查询2.
Array
(
[0] => Array
(
[Purchase] => Array
(
[date_generated] => 1970-01-01
)
)
[1] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-17
)
)
[2] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-18
)
)
[3] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-19
)
)
[4] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-22
)
)
[5] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-29
)
)
[6] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-08-01
)
)
)
查询2 :仅添加了' Purchase.id'
$this->Purchase->find('all',array(
'order' => array('Purchase.date_generated ASC'),
'fields' => array('DISTINCT Purchase.date_generated','Purchase.id')));
查询2的结果:在此结果数组索引5,6,7 date_generated重复。
Array
(
[0] => Array
(
[Purchase] => Array
(
[date_generated] => 1970-01-01
[id] => 9
)
)
[1] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-17
[id] => 1
)
)
[2] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-18
[id] => 2
)
)
[3] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-19
[id] => 3
)
)
[4] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-22
[id] => 4
)
)
[5] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-29
[id] => 5
)
)
[6] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-29
[id] => 6
)
)
[7] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-06-29
[id] => 7
)
)
[8] => Array
(
[Purchase] => Array
(
[date_generated] => 2014-08-01
[id] => 8
)
)
)
答案 0 :(得分:3)
这似乎是标准的sql行为。第一个查询产生类似这样的东西
选择 DISTINCT Purchase.date_generated 从 采购 订购 Purchase.date_generated ASC
第二个产生类似
的查询选择 DISTINCT Purchase.date_generated, Purchase.id 从 采购 订购 Purchase.date_generated ASC
这些查询的结果正是您所获得的。对于socond,它将返回不同的Purchase.date_generated和Purchase.id对。因此,如果某个日期有几个购买ID,则每个购买ID都是不同的对。
因此,如果您仅在明确日期之后,则应使用第一个查询。