tags:

views:

26

answers:

2

Lets say I have a table with 20 entries. They are sorted by date (date is a column name >_>) in descending order. How would I go about selecting ONLY the newest entry and the 15th oldest entry?

I am getting all 15 results by doing the following query

SELECT * FROM mytable m WHERE col1 = "zzz" ORDER BY date DESC LIMIT 15;
A: 

you may need to use UNION of two SELECTs

(SELECT * FROM mytable m WHERE col1 = "zzz" ORDER BY date LIMIT 1, 15)
UNION
(SELECT * FROM mytable m WHERE col1 = "zzz" ORDER BY date DESC LIMIT 1)

UPDATE:

added parenthesis

praksant
Only one ORDER BY is allowed when using a UNION...
OMG Ponies
You were right, but with parenthesis that i just added it works - just tried it
praksant
+2  A: 

Use:

SELECT x.*
  FROM (SELECT a.*,
               @rownum := @rownum + 1 AS rank
          FROM mytable a 
          JOIN (SELECT @rownum := 0) r
         WHERE a.col1 = "zzz" 
      ORDER BY a.date DESC) x
 WHERE x.rank IN (1, 15)
OMG Ponies
Hmm, I'm getting "Unknown table 'a'"
Scotta
@Scotta: Oops - corrected table alias typo.
OMG Ponies
Ah, thanks very much!
Scotta