Hello to all!
I have a problem with a SQL statement: Using this
select a.id as ID, a.dur as DUR, DATE(FROM_UNIXTIME(timestampCol)) as date,
a_au.re as RE, a_au.stat as STAT from b_c
inner join c on b_c.c_id = c.id
inner join a on c.id = a.c_id
inner join a_au on a.id = a_au.id
inner join revi on a_au.rev = revi.rev
where b_c.b_id = 5
I get this result:
ID DUR date RE STAT
-------------------------------
31, 10, '2010-07-14', 2200, 0
31, 10, '2010-07-14', 2205, 0
31, 10, '2010-07-14', 2206, 2
31, 10, '2010-07-14', 2207, 0
31, 10, '2010-07-14', 2210, 2
31, 10, '2010-07-15', 2211, 0
31, 10, '2010-07-14', 2213, 1
32, 10, '2010-07-14', 2203, 0
32, 10, '2010-07-14', 2204, 0
32, 10, '2010-07-14', 2208, 2
32, 10, '2010-07-14', 2209, 0
32, 10, '2010-07-15', 2212, 2
Now I want to get one result row for one ID and date combination. Also I want to get this result row with the highest RE number.
So I write my statement:
select a.id as ID, a.dur as DUR, DATE(FROM_UNIXTIME(timestampCol)) as date,
max(a_au.re) as RE, a_au.stat as STAT from b_c
inner join c on b_c.c_id = c.id
inner join a on c.id = a.c_id
inner join a_au on a.id = a_au.id
inner join revi on a_au.rev = revi.rev
where b_c.b_id = 5
group by ID, date
Now I get this result:
ID DUR date RE STAT
-------------------------------
31, 10, '2010-07-14', 2213, 0
31, 10, '2010-07-15', 2211, 0
32, 10, '2010-07-14', 2209, 0
32, 10, '2010-07-15', 2212, 2
Everything seems to be okay, I have one result row per day/ID combination and the row with the highest RE number. But: the column STAT does not have the correct values! The row
31, 10, '2010-07-14', 2213, 0
must have the status 1:
31, 10, '2010-07-14', 2213, 1
So there must be a mistake in my statement. It seems that MySQL takes the first STAT column value it found. But I want to have the corresponding one.
What should I do? I saw other topics about this like here: http://stackoverflow.com/questions/1305056/mysql-selecting-all-corresponding-fields-using-max-and-group-by but I can not transfer it to my SQL statement.
Thanks a lot in advance & Best Regards.