views:

181

answers:

3
SELECT
    number, count(id)
FROM
    tracking
WHERE
    id IN (SELECT max(id) FROM tracking WHERE splitnr = 'a11' AND number >0 AND timestamp >= '2009-04-08 00:00:00' AND timestamp <= '2009-04-08 12:55:57' GROUP BY ident)
GROUP BY
    number
A: 

How about this:

SELECT    number, count(id)
FROM    tracking 
  INNER JOIN (SELECT max(id) ID FROM tracking  
                 WHERE splitnr = 'a11' AND 
                       number >0 AND timestamp >= '2009-04-08 00:00:00' AND 
                       timestamp <= '2009-04-08 12:55:57'
              GROUP BY ident
             ) MID ON (MID.ID=tracking.id)
WHERE   
GROUP BY number
JohnFx
You need to add GROUP BY ident into the inner subquery.
Quassnoi
You sure about that? I don't think it is needed.
JohnFx
The OP changed the question, the inner GROUP BY is needed under the new version so I added it back.
JohnFx
Wasn't the question "instead of a subquery", this is definately a refactor of the original query, but still uses a sub query...
Dems
Technically it uses a derrived table and not a subquery.
JohnFx
DEMs the use of a derived table instead of a subquery is a standard performance improvement technique. A derived table acts on the set of rows and a correlated subquery runs row by row.
HLGEM
A: 

Slightly hard to make sure that I've got it entirely right without seeing the data and knowing exactly what you're trying to achieve but personally I'd turn the sub-query into a view and then join on that, so:

create view vMaximumIDbyIdent

as

SELECT ident, max(id) maxid

FROM tracking

WHERE splitnr = 'a11' AND number >0

AND timestamp >= '2009-04-08 00:00:00'

AND timestamp <= '2009-04-08 12:55:57'

GROUP BY ident

then:

SELECT

number, count(id)

FROM

tracking,

vMaximumIDbyIdent

WHERE

tracking.id = vMaximumIDbyIdent.maxid

GROUP BY

number

More readable and maintainable.

A: 

Could you not do something like:

SELECT
    number,
    count(id)
FROM
    tracking
WHERE
    splitnr = 'a11' AND number > 0 AND timestamp >= '2009-04-08 00:00:00' AND timestamp <= '2009-04-08 12:55:57'
GROUP BY
    number
ORDER BY
    number DESC
LIMIT 0,1

(I don't really know MySQL by the way)

I'm assuming this would give you back the same resultset, you order it by the number desc because you want the maximum one, right? Then you can put the WHERE clause in and limit it by one to give you the first one which is essentially the same as MAX (I think) Thus removing the JOIN altogether.

EDIT: I didn't think you'd need the GROUP BY identd either

Kezzer