1

有没有办法在不使用自连接的情况下解决这样的问题?使用 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

4 回答 4

2

答案是“是”。你可以通过聚合来做到这一点。关键是使用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 上进行了测试。

于 2013-08-23T00:34:28.570 回答
0

我不知道我是否理解正确,但是:

SELECT * 
  FROM test 
 WHERE currentTime IN (SELECT MIN(currentTime) FROM test)
于 2013-08-22T23:37:38.423 回答
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)
于 2013-08-22T23:36:57.040 回答
-1

How about this:

SELECT
    *
FROM
    test
ORDER BY
    currentTime
LIMIT
    1;

Would this work for your purposes?

于 2016-04-20T22:55:08.577 回答