开发者

Select from a certain row and onwards with mysql

开发者 https://www.devze.com 2023-04-06 04:49 出处:网络
How can I select from a certain row and onwards? For instance, the table I want to query, pg_idpg_titlepg_backdate

How can I select from a certain row and onwards?

For instance, the table I want to query,

pg_id   pg_title    pg_backdate
1       a           2012-09-18 13:32:49
2       b           2011-09-18 13:32:49
3       c           2011-06-18 13:32:49
4       d           2010-05-18 13:32:49
5       e           2009-04-18 13:32:49
6       f           2011-10-18 13:32:49
7       g           2012-04-18 13:32:49
8       h           2012-09-18 13:32:49
9       i           2012-10-18 13:32:49

I want to select the top 5 rows only, starting from current month and year and onwards, I have worked on the query below - it only selects the top 5 of current month and current year but not the rows onwards,

SELECT *
    FROM root_pages AS p

    WHERE DATE_FORMAT(开发者_如何学运维p.pg_backdate, '%Y') = '2011'
    AND DATE_FORMAT(p.pg_backdate, '%m') = '09' 

    ORDER BY p.pg_backdate DESC

    LIMIT 5

Ideally, it should return these rows only,

pg_id   pg_title    pg_backdate
1       a           2012-09-18 13:32:49
2       b           2011-09-18 13:32:49
6       f           2011-10-18 13:32:49
7       g           2012-04-18 13:32:49
8       h           2012-09-18 13:32:49


SELECT *
FROM root_pages AS p
WHERE p.pg_backdate >= '2011-09-01'
ORDER BY p.pg_backdate DESC
LIMIT 5

Using functions like you do will kill any chance MySQL has of using an index.

If you want to select the top 5 from the month do:

SELECT *
FROM root_pages AS p
WHERE p.pg_backdate BETWEEN '2011-09-01' AND '2011-09-30'
ORDER BY p.pg_backdate DESC
LIMIT 5

If you want the top 5 in the month and the rows beyond, then do

  SELECT *
  FROM root_pages AS p
  WHERE p.pg_backdate BETWEEN '2011-09-01' AND '2011-09-30'
  ORDER BY p.pg_backdate DESC
  LIMIT 5
UNION ALL
  SELECT *
  FROM root_pages AS p
  WHERE p.pg_backdate > '2011-09-30'
  ORDER BY p.pg_backdate DESC


SELECT *
FROM root_pages
WHERE pg_backdate >= '2011-09-01'
ORDER BY pg_backdate
LIMIT 0, 5

The above query will return 5 rows starting from 1st day of September 2011 and onwards. An ORDER BY clause will return the dates closest to that date. You can generate the date (1st of current month) via PHP - or - you can have MySQL do that for you:

SELECT *
FROM root_pages
WHERE pg_backdate >= CAST(CONCAT_WS('-', YEAR(CURRENT_TIMESTAMP), MONTH(CURRENT_TIMESTAMP), 1) AS DATE)
ORDER BY pg_backdate
LIMIT 0, 5


He wants to order by id it seems...

SELECT * 
FROM (
SELECT * 
FROM root_pages AS p
WHERE p.pg_backdate >=  '2011-09-01'
ORDER BY p.pg_backdate DESC 
LIMIT 5
) AS sub
ORDER BY sub.pg_id
0

精彩评论

暂无评论...
验证码 换一张
取 消