2016-04-26 71 views
-2

如何從mysql數據庫中刪除表中的行,刪除後我應該在列中有4個不同的值。從條件刪除mysql

我的數據庫的實際狀態:

+----+-----------+---------+---------------------+ 
| 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 | 
+----+-----------+---------+---------------------+ 

我想結束了:

+----+-----------+---------+---------------------+ 
| 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 | 
+----+-----------+---------+---------------------+ 
+1

你想保留哪些? – shmosel

+2

可能重複[如何刪除MySQL表上的重複?](http://stackoverflow.com/questions/2630440/how-to-delete-duplicates-on-a-mysql-table) –

回答

1

您可以用這種方式

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); 
+0

錯誤 - 您可以' t在FROM子句 –

+0

@MaxP中指定目標表'...'進行更新。這不是一個更新,這是一個刪除.. – scaisEdge

+0

我知道,當我嘗試執行此查詢時出現此錯誤 –

1

這樣的查詢與保存的行每個action_id的最大temps_action,價格

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); 
+0

#1093 - 您無法指定目標表'...'在FROM子句更新 –

+0

我已更新答案 – splash58

+0

@Max P它可以是通過添加子查詢來創建 – splash58

0

你真的想要做的是刪除重複的行。這裏有一個示例查詢,可以幫助你:

DELETE FROM TableName 
WHERE valeurs IN (SELECT * 
      FROM (SELECT valeurs FROM TableName 
        GROUP BY valeurs 
HAVING (COUNT(*) > 1) AS Something 
       ) 
      ); 
+0

錯誤#1248 - 每個派生表必須有它自己的別名 –