smont
smont

Reputation: 1348

Selecting two specific mysql table rows in a single query

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;

Upvotes: 0

Views: 98

Answers (2)

OMG Ponies
OMG Ponies

Reputation: 332791

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)

Upvotes: 2

marianboda
marianboda

Reputation: 764

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

Upvotes: 0

Related Questions