如何删除“之前”发生某些键值的行?

时间:2010-08-31 11:39:39

标签: sql mysql

我的观点看起来像这样:

mysql> select * from p2;
+---+---------+---------+
| k | measure | time_id |
+---+---------+---------+
| D |     200 |       2 |
| E |     201 |       2 |
| F |     203 |       2 |
| A |      20 |       1 |
| B |      22 |       1 |
| C |      23 |       1 |
| D |     100 |       1 |
| E |     101 |       1 |
| F |     103 |       1 |
| G |       4 |       1 |
| H |       7 |       1 |
| I |      10 |       1 |
+---+---------+---------+

(k, time_id)是一个唯一键,上面的内容大大简化了(time_idk会有更多的值)。排序顺序为time_id DESC(后跟k ASC,但这并不重要。)

我想找到一个SELECT语句,将其过滤到这个:

+---+---------+---------+
| k | measure | time_id |
+---+---------+---------+
| D |     200 |       2 |
| E |     201 |       2 |
| F |     203 |       2 |
| A |      20 |       1 |
| B |      22 |       1 |
| C |      23 |       1 |
| G |       4 |       1 |
| H |       7 |       1 |
| I |      10 |       1 |
+---+---------+---------+

我想通过过滤掉之前已使用k值的行来确保列k的值是唯一的。

在此示例中,在原始视图中,行0,1,2包含k值D,E和F,但行6,7,8也是如此,因此删除行6-8以生成第二个视图。 / p>

是否有可以执行此操作的SELECT语句?感觉它应该是直截了当的,但我无法弄清楚如何去做。

2 个答案:

答案 0 :(得分:2)

  select * from p2 e
      join (select k, Max(time_id) time_id 
            from p2
            group by k) t
      ON (e.k = t.k and e.time_id = t.time_id)

答案 1 :(得分:1)

您可能想要使用派生表:

SELECT p2.* 
FROM   p2
JOIN   (
           SELECT    MAX(time_id) max_time, k 
           FROM      p2 
           GROUP BY  k
       ) d_p2 ON (d_p2.k = p2.k AND d_p2.max_time = p2.time_id);

或者您也可以使用“null-self-join”方法:

SELECT    p2.*
FROM      p2
LEFT JOIN p2 AS d_p2 ON d_p2.k = p2.k AND d_p2.time_id > p2.time_id
WHERE     d_p2.k IS NULL;

只要您确定time_id对每个k都是唯一的,这些就可以正常运行。否则你仍然可以获得重复的行。

测试用例:

CREATE TABLE p2 (k char(1), measure int, time_id int);

INSERT INTO p2 VALUES ('D', 200, 2);
INSERT INTO p2 VALUES ('E', 201, 2);
INSERT INTO p2 VALUES ('F', 203, 2);
INSERT INTO p2 VALUES ('A',  20, 1);
INSERT INTO p2 VALUES ('B',  22, 1);
INSERT INTO p2 VALUES ('C',  23, 1);
INSERT INTO p2 VALUES ('D', 100, 1);
INSERT INTO p2 VALUES ('E', 101, 1);
INSERT INTO p2 VALUES ('F', 103, 1);
INSERT INTO p2 VALUES ('G',   4, 1);
INSERT INTO p2 VALUES ('H',   7, 1);
INSERT INTO p2 VALUES ('I',  10, 1);

结果:

+------+---------+---------+
| k    | measure | time_id |
+------+---------+---------+
| D    |     200 |       2 |
| E    |     201 |       2 |
| F    |     203 |       2 |
| A    |      20 |       1 |
| B    |      22 |       1 |
| C    |      23 |       1 |
| G    |       4 |       1 |
| H    |       7 |       1 |
| I    |      10 |       1 |
+------+---------+---------+
9 rows in set (0.00 sec)