MySQL-如何选择相应列值的第一个重复行

时间:2014-11-18 17:48:36

标签: mysql

我有一个包含三列(A,B,C)的表。所有列都是数据类型varchar()。这里我只想选择那些初始行,它们是列A的第一个重复值。就像列A具有不同的值(1,2,3)所以列中值为1的初始行需要检索。我的数据集中没有时间戳列。

For value 1 in column A, i need to retrieve row that has 1,2,1 value for column (A,B,C)
For value 2 in column A, i need to retrieve row that has 2,4,1 value for column (A,B,C)
For value 3 in column A, i need to retrieve row that has 3,1,1 value for column (A,B,C)

A|B|C
-----  
1|2|1
3|1|2
3|3|1
2|4|1
3|1|2
3|1|4
1|2|3

Now i want a Output Table as describe below.

A|B|C
-----
1|2|1
3|1|2
2|4|1

1 个答案:

答案 0 :(得分:3)

请考虑以下事项。为简单起见,我使用了auto_incrementing id,但是一个独特的时间戳也能正常工作......

 DROP TABLE IF EXISTS my_table;

 CREATE TABLE my_table 
 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
 ,A INT NOT NULL
 ,B INT NOT NULL
 ,C INT NOT NULL 
 ,UNIQUE(a,b,c)
 );

 INSERT INTO my_table (a,b,c) VALUES
 (1 ,2 ,1),
 (1 ,1 ,2),
 (2 ,3 ,1),
 (2 ,4 ,1),
 (3 ,1 ,2),
 (3 ,1 ,4),
 (3 ,2 ,3);

 SELECT x.* FROM my_table x ORDER BY id;
 +----+---+---+---+
 | id | A | B | C |
 +----+---+---+---+
 |  1 | 1 | 2 | 1 |
 |  2 | 1 | 1 | 2 |
 |  3 | 2 | 3 | 1 |
 |  4 | 2 | 4 | 1 |
 |  5 | 3 | 1 | 2 |
 |  6 | 3 | 1 | 4 |
 |  7 | 3 | 2 | 3 |
 +----+---+---+---+

 SELECT x.* 
   FROM my_table x 
   JOIN 
      ( SELECT a
             , MIN(id) min_id 
          FROM my_table 
         GROUP 
            BY a
      ) y 
     ON y.a = x.a 
    AND y.min_id = x.id 
  ORDER 
     BY id;
 +----+---+---+---+
 | id | A | B | C |
 +----+---+---+---+
 |  1 | 1 | 2 | 1 |
 |  3 | 2 | 3 | 1 |
 |  5 | 3 | 1 | 2 |
 +----+---+---+---+

有关此消息的更多信息,请参阅手册(http://dev.mysql.com/doc/refman/5.1/en/example-maximum-column-group-row.html)。