-2

how can I delete rows from this table in mysql database that after the delete I should have 4 distinct values in the column valeurs .

the actual state of my database :

+----+-----------+---------+---------------------+
| id | action_id | valeurs | temps_action        |
+----+-----------+---------+---------------------+
| 81 |         1 | ON_1    | 2016-04-26 11:14:43 |
| 80 |         2 | OFF_2   | 2016-04-26 11:14:41 |
| 84 |         2 | OFF_2   | 2016-04-26 11:14:48 |
| 83 |         1 | ON_1    | 2016-04-26 11:14:46 |
| 79 |         1 | OFF_1   | 2016-04-26 11:14:40 |
| 78 |         2 | ON_2    | 2016-04-26 11:14:38 |
| 77 |         1 | ON_1    | 2016-04-26 11:14:35 |
| 82 |         2 | OFF_2   | 2016-04-26 11:14:45 |
+----+-----------+---------+---------------------+

I want to end up with :

+----+-----------+---------+---------------------+
| id | action_id | valeurs | temps_action        |
+----+-----------+---------+---------------------+
| 81 |         1 | ON_1    | 2016-04-26 11:14:43 |
| 80 |         2 | OFF_2   | 2016-04-26 11:14:41 |
| 79 |         1 | OFF_1   | 2016-04-26 11:14:40 |
| 78 |         2 | ON_2    | 2016-04-26 11:14:38 |
+----+-----------+---------+---------------------+
Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
ghina
  • 25
  • 2
  • 6

3 Answers3

1

You can use this way

delete from   my_table  as t
where (t.id, t.valeurs) not  in ( select max(t2.id), t2.valeurs 
                            from my_table as t2
                             group by valeurs); 
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

such query saves the rows with max temps_action for each action_id, valeurs

delete 
    from  my_table 
  where (action_id, temps_action, valeurs) not in 
      (select * from (select action_id, max(temps_action), valeurs 
             from my_table 
          group by action_id, valeurs) t1); 
splash58
  • 26,043
  • 3
  • 22
  • 34
0

What you're really trying to do is to remove duplicate rows. Here's an example query that could help you with that:

DELETE FROM TableName  
WHERE valeurs IN (SELECT * 
             FROM (SELECT valeurs FROM TableName 
                   GROUP BY valeurs
 HAVING (COUNT(*) > 1) AS Something
                  ) 
            );
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Auguste
  • 2,007
  • 2
  • 17
  • 25