Forum Moderators: coopster

Message Too Old, No Replies

How do you select the max/min value from a large table?

"ORDER BY column DESC LIMIT 0, 1" - too slow.

         

iProgram

1:17 pm on Aug 10, 2005 (gmt 0)

10+ Year Member



I use
SELECT id FROM tab ... ORDER BY age DESC LIMIT 0, 1
or
SELECT id FROM tab ... ORDER BY age ASC LIMIT 0, 1

Is there other method to do that?

arran

2:39 pm on Aug 10, 2005 (gmt 0)

10+ Year Member



Hi iProgram,

Try:

select min(ID) from tableA

select max(ID) from tableA

Although i'm guessing the real problem is that you don't have an index on ID. If you did, mysql wouldn't have to tablescan for the aggregate functions (min/max) or build a worktable for the 'order by'.

arran.

iProgram

3:27 pm on Aug 10, 2005 (gmt 0)

10+ Year Member



Do you mean
SELECT max(age) from table? And I should create an index on age column?

arran

3:50 pm on Aug 10, 2005 (gmt 0)

10+ Year Member



Exactly.

Sorry about the typo :(

dcrombie

3:51 pm on Aug 10, 2005 (gmt 0)



SELECT MIN(age) AS min, MAX(age) AS max FROM table;

;)

iProgram

1:07 am on Aug 11, 2005 (gmt 0)

10+ Year Member



New question. How do you select max/min N results from a large table?

For example, I want to display some in-house ADs base on impressions, three step2:

1. SELECT id FROM tab ORDER BY impression ASC LIMIT 0, 2;
(Get two ADs with minimum impressions)

2. $id1=id of AD1, $id2=id of AD2

3. UPDATE tab SET impressoion=impression+1 WHERE id=$id1 or id=$id2 LIMIT 2

According to mysql doc, I should create an index on impression column, but it will make the UPDATE step too slow. Any alternate method?

coopster

3:16 am on Aug 12, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You can create more than one index ;)