mySql:返回错误的结果

时间:2016-04-25 09:47:44

标签: mysql

我有这张桌子:

product_id | name   |  status   |update_date
___________|________|___________|___________
   1       | prod1  | bought    | 2016-04-20
   2       | prod2  | bought    | 2016-04-20
   3       | prod3  | bought    | 2016-04-20
   1       | prod1  | sold      | 2016-04-22

我执行以下查询:

select status, max(update_date), product_id from product group by product_id;

我得到了这个结果:

bought| 2016-04-22 12:25:00 |   1
bought| 2016-04-20 10:10:10 |   2
bought| 2016-04-20 10:10:10 |   3

我想知道为什么对于product_id = 1的产品,我得到的状态是买了而不是卖掉!!

我想获得每种产品的最后状态。

3 个答案:

答案 0 :(得分:3)

因为如果您选择既不在组子句中也不与min()max()等函数聚合的列...您将从组中的可用值中获取任何值。

MySQL的这个功能令人困惑,这也是其他数据库引擎使用此查询返回错误的原因,因为status未聚合。

答案 1 :(得分:2)

试试这个:

SELECT 
P.status,
P.update_date,
P.product_id
FROM product P
INNER JOIN 
(
select 
max(update_date) max_time, 
product_id 
from product 
group by product_id ) t
ON P.product_id = t.product_id AND P.update_date = t.max_time

它属于这一类:选择具有最大值的全行

请查看此POST

答案 2 :(得分:1)

试试这个

select product_id, status, max(update_date) from product where (product_id,update_date) IN (select product_id, max(update_date) from product group by product_id)group by product_id, status