-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
  • 19,374
  • 2
  • 54
  • 107
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
  • 129,293
  • 10
  • 87
  • 97
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
  • 25,715
  • 3
  • 20
  • 32
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,372
  • 15
  • 66
  • 132
Auguste
  • 1,797
  • 2
  • 15
  • 24