0

I have this table:

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

I execute the following query:

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

I get this result:

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

I wonder why for the product with product_id = 1, I get the status bought and not sold!!

I wanna get the last status for each product.

senior
  • 2,196
  • 6
  • 36
  • 54

3 Answers3

3

Because if you select columns that are neither in the group clause nor be aggregated with functions like min(), max()... you get any value from the available ones in the group.

This feature of MySQL is confusing and that is why other DB engines return an error using this query because status is not aggregated.

juergen d
  • 201,996
  • 37
  • 293
  • 362
2

Try this:

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

It lies in this category : SELECT THE WHOLE ROW HAVING THE MAX VALUE.

Please look at this POST

Community
  • 1
  • 1
1000111
  • 13,169
  • 2
  • 28
  • 37
1

try this

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
JYoThI
  • 11,977
  • 1
  • 11
  • 26