首次出现mysql中的特定值

时间:2013-06-06 13:40:59

标签: mysql

我错过了一层我认为不相关的复杂性,但它似乎是因为MIN()建议似乎无法解决这个问题。

我有一张表格如下:

col-1 | col-b | col-c | col-d
----------------------------------
mhm1  | a     | 09:20 | 2013-09-21
mhm1  | b     | 09:21 | 2013-09-20
mhm1  | c     | 09:22 | 2013-09-19
mhm1  | c     | 09:23 | 2013-09-18
mhm1  | d     | 09:24 | 2013-09-19
mhm2  | a     | 09:25 | 2013-09-21
mhm2  | c     | 09:26 | 2013-09-20
mhm2  | d     | 09:27 | 2013-09-19
mhm2  | c     | 09:28 | 2013-09-18

我想查询返回每个唯一col-1的第一行,其中col-b ='c'。

e.g。

col-1 | col-b | col-c | col-d
---------------------------------
mhm1  | c     | 09:23 | 2013-09-18
mhm2  | c     | 09:28 | 2013-09-18

实现此目的的适当SQL-Request是什么? 我试过了:

SELECT col-a, col-b, min(col-c), min(col-d) FROM MY TABLE
WHERE col-b = 'c'
GROUP BY col-a
ORDER BY col-c ASC

但我明白了:

col-1 | col-b | col-c | col-d
---------------------------------
mhm1  | c     | 09:22 | 2013-09-18
mhm2  | c     | 09:26 | 2013-09-18

这不是我想要的。

由于

3 个答案:

答案 0 :(得分:0)

使用MIN() function告诉MySQL,您希望该组中的值最低。

SELECT col-a, col-b, MIN(col-c) FROM MY_TABLE
WHERE col-b = 'c'
GROUP BY col-a
/* ORDER BY col-c ASC <-- this is not necessary*/

这将适用于您的示例。但它可能很危险。其他列值不需要属于具有最小col-c值的那一行。要实现这一点,您必须按如下方式编写:

SELECT col-a, col-b, col-c FROM MY_TABLE t
WHERE col-b = 'c'
AND col-c = (SELECT MIN(col-c) FROM yourTable yt WHERE yt.col-a = t.col-a)
GROUP BY col-a

有关更多示例,请参阅此manual entry

答案 1 :(得分:0)

我认为您可以使用MIN()函数来实现此目标

SELECT col-1, col-b, MIN(col-c)
FROM MY TABLE
WHERE col-b = 'c'
GROUP BY col-1
ORDER BY col-c ASC

Live SQLFiddle

答案 2 :(得分:0)

DROP TABLE IF EXISTS my_test;

CREATE TABLE my_test (col1 CHAR(4) NOT NULL,colb CHAR(1) NOT NULL,colc TIME NOT NULL,PRIMARY KEY(col1,colb,colc));

INSERT INTO my_test VALUES
('mhm1','a','09:20:00'),
('mhm1','b','09:21:00'),
('mhm1','c','09:22:00'),
('mhm1','c','09:23:00'),
('mhm1','d','09:24:00'),
('mhm2','a','09:25:00'),
('mhm2','c','09:26:00'),
('mhm2','d','09:27:00'),
('mhm2','c','09:28:00');

SELECT x.* 
  FROM my_test x 
  JOIN 
     ( SELECT col1,colb,MIN(colc) min_colc FROM my_test GROUP BY col1,colb) y 
    ON y.col1 = x.col1 
   AND y.colb=x.colb 
   AND y.min_colc = x.colc 
WHERE x.colb = 'c';
+------+------+----------+
| col1 | colb | colc     |
+------+------+----------+
| mhm1 | c    | 09:22:00 |
| mhm2 | c    | 09:26:00 |
+------+------+----------+