使用mysql从某一行开始选择

时间:2011-09-21 12:31:08

标签: mysql select

如何从某一行开始选择?

例如,我要查询的表,

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

我想只选择前5行,从当前月份和年份开始,我已经处理了下面的查询 - 它只选择当前月份和当前年份的前5名,而不是选择以后的行,

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

理想情况下,它应仅返回这些行,

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

3 个答案:

答案 0 :(得分:3)

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

使用像你这样的函数会杀死MySQL使用索引的任何机会。

如果您想从月份中选择前5名:

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

如果您希望月份中的前五名超出行数,那么

  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

答案 1 :(得分:0)

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

上述查询将从2011年9月1日起开始返回5行。 ORDER BY子句将返回最接近该日期的日期。您可以通过PHP生成日期(当月的第1天) - 或者 - 您可以让MySQL为您执行此操作:

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

答案 2 :(得分:0)

他想通过id订购......

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