I’m having trouble getting MySQL to return a query properly.
Here’s my data:
id date value
2 2011-01-04 55.66
2 2011-03-23 22.33
2 2011-04-21 9.44
5 2010-01-04 104.55
5 2011-02-03 38.82
... ... ...
i’m trying to get a query to return:
select t1.id, max(t1.date), t1.value, t2.id, min(t2.date), t2.value
from tab1 as t1, tab1 as t2
where t1.id = t2.id
and t1.date <= '2011-03-31'
and t2.date >= '2011-04-01'
group by t1.id;
But it is taking forever (db has ~ 1mm lines). I’ve tried various joins but then it seems to ignore the date < and > statements. Basically I want each customers last purchase date and amount before 4/1/2011 and their first purchase and date on or after 4/1/2011. Any suggestions would be great.
Your query is flawed, the columns t1.value and max(t1.date) do not have a relation to one and other.
You need to rewrite it as follows, if you want to know the total purchases per the date selected.
Make sure you have an index on
idanddateRemarks
idis generally understand as a shorthand for the primary key.Having a field called
idthat does not a unique index, is confusing and widely considered a code smell.