目前我在使用PHP和MySQL时遇到了一个非常奇怪的问题。
我有一个数据表,我正在尝试按日期排序。但是遇到了两件奇怪的事情:
这是我的命令:
SELECT DISTINCT a.id
FROM orders as a, companies as b, orderProducts as e
WHERE a.companyId = b.id AND a.id = e.orderId AND a.deleted = 0 AND a.id <> 0
ORDER BY a.dateReceived DESC
LIMIT 45, 15
当通过phpMyAdmin完成时,命令似乎按预期工作;它保留了相同的顺序,但通过PHP改变它。
这是我打印ID的代码所以我不认为它是PHP中的东西。
$result = mysql_query( $query ) or die( 'A mysql error has occured: ' . mysql_error(). $query );
$ids = array();
while($row = mysql_fetch_assoc($result)) {
$ids[]=$row['id'];
}
if( $_GET['debug'] == "true" ) {
echo "Query: ".$query." IDs: ";
print_r( $ids );
}
也许这与那些连接有关?
有什么想法吗?
答案 0 :(得分:0)
您的查询:
SELECT DISTINCT a.id
FROM orders as a, companies as b, orderProducts as e
WHERE a.companyId = b.id AND a.id = e.orderId AND a.deleted = 0 AND a.id <> 0
ORDER BY a.dateReceived DESC
LIMIT 45, 15
正在distinct
上执行id
,但随后按dateReceived
排序。在大多数SQL方言中,这将是一个错误,因为order by
后distinct
列不可用。 MySQL会选择一个任意值,这可能是导致问题的原因。
以下使用显式聚合和max()
来解决此问题:
SELECT a.id
FROM orders as a, companies as b, orderProducts as e
WHERE a.companyId = b.id AND a.id = e.orderId AND a.deleted = 0 AND a.id <> 0
GROUP BY a.id
ORDER BY max(a.dateReceived) DESC
LIMIT 45, 15;