在单个查询中选择两个特定的mysql表行

时间:2010-05-11 21:57:07

标签: mysql

假设我有一张包含20个条目的表格。它们按日期(日期是列名> _>)按降序排序。我如何才能选择最新的条目和第15个最老的条目?

我通过执行以下查询获得所有15个结果

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

2 个答案:

答案 0 :(得分:2)

使用:

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)

答案 1 :(得分:0)

您可能需要使用两个SELECT的UNION

(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)

更新:

添加括号