检索具有最小日期的行中的所有列?

时间:2013-08-22 23:25:35

标签: mysql sql date min

有没有办法解决这样的问题,而不使用自我加入?某种方式使用min()函数?

我想获得每组c1和c2列的第一个水果条目。 (假设日期不能相同)

DROP TABLE IF EXISTS test;
CREATE TABLE test
(
    c1 varchar(25),
    c2 varchar(25),
    fruit varchar(25),
    currentTime Datetime
);
INSERT INTO test VALUES    
('a','b','pineapple','2013-01-28 20:50:00'),
('a','b','papaya','2013-01-28 20:49:00'),
('a','b','pear','2013-01-28 20:51:00'),
('a','c','peach','2013-01-28 18:12:00'),    
('a','c','plum','2013-01-28 20:40:00'),
('a','c','pluot','2013-01-28 16:50:00');

这是我当前的查询:

SELECT t2.* 
  FROM (SELECT c1,
               c2,
               MIN(currentTime) AS ct
          FROM test 
      GROUP BY c1, c2) as t1
  JOIN test t2
    ON t1.c1 = t2.c1 AND
       t1.c2 = t2.c2 AND
       t2.currentTime = t1.ct

这会产生每个c1/c2对的最早条目,但有没有办法使用min()并避免自我加入?

4 个答案:

答案 0 :(得分:1)

答案是肯定的。你只需聚合即可完成。关键是使用group_concat() / substring_index()技巧获得第一个成果:

select c1, c2,
       substring_index(group_concat(fruit order by currentTime), ',', 1) as fruit,
       min(currentTime)
from test
group by c1, c2;

已在您的SQL Fiddle上测试过。

答案 1 :(得分:0)

  SELECT c1,
         c2,
         currentTime AS ct
    FROM test
GROUP BY c1,c2 
HAVING MIN(ct)

或者,如果您想获得fruit列,请尝试:

  SELECT c1,
         c2,
         fruit,
         currentTime AS ct
    FROM test
GROUP BY c1,c2 
HAVING MIN(ct)

答案 2 :(得分:0)

我不知道我是否理解你,但是:

SELECT * 
  FROM test 
 WHERE currentTime IN (SELECT MIN(currentTime) FROM test)

答案 3 :(得分:-1)

这个怎么样:

SELECT
    *
FROM
    test
ORDER BY
    currentTime
LIMIT
    1;

这是否适用于您的目的?