2017-05-12 107 views
-1

爲什麼MySQL沒有通過這個查詢刪除條目?爲什麼條目不被刪除?

DELETE FROM transport_cms.page WHERE Id IN (SELECT * FROM (SELECT g.Id FROM transport_cms.page g, transport_cms.page p where g.Url = p.Url and g.Site_id = p.Site_id and g.Id != p.Id group by p.Site_id) AS p); 
+0

是什麼告訴你的原因是什麼?你只需要首先運行'SET SQL_SAFE_UPDATES = 0;'然後用子查詢等來運行你的delete語句? –

+0

您查詢不正確。提供適當的問題來解決問題 –

+0

我想刪除表transport_cms.page中的dublicate條目。 Dublicate - 當Url字段相同時,Site_id字段相等,但Id不相等。 – destroyer25t

回答

0
SELECT g.Id FROM transport_cms.page g, transport_cms.page p where g.Url = p.Url and g.Site_id = p.Site_id and g.Id != p.Id group by p.Site_id 

這個腳本是無效的。 select不能包含不在group中的字段。

0

您的查詢字詞部分工作: -

drop table if exists transport_cms_page; 

create table transport_cms_page (id int,url varchar(3),site_id int); 

insert into transport_cms_page values 
(1,'aaa',1),(2,'aaa',1), (3,'aaa',1); 

MariaDB [sandbox]> DELETE FROM transport_cms_page 
    -> WHERE Id IN (
    -> SELECT * FROM (
    -> SELECT g.Id 
    -> FROM transport_cms_page g, transport_cms_page p 
    -> where g.Url = p.Url and g.Site_id = p.Site_id and p.Id <> g.Id 
    -> group by p.Site_id 
    ->) AS p 
    ->); 
Query OK, 1 row affected (0.03 sec) 

MariaDB [sandbox]> 
MariaDB [sandbox]> select * from transport_cms_page; 
+------+------+---------+ 
| id | url | site_id | 
+------+------+---------+ 
| 1 | aaa |  1 | 
| 3 | aaa |  1 | 
+------+------+---------+ 
2 rows in set (0.00 sec) 

當您運行查詢,這可能是更適合

MariaDB [sandbox]> DELETE FROM transport_cms_page 
    -> WHERE Id not IN 
    -> (
    -> select minid 
    -> from 
    -> (select url,site_id, min(id) minid 
    -> from transport_cms_page 
    -> group by url,site_id 
    ->) m 
    ->); 
Query OK, 2 rows affected (0.02 sec) 

MariaDB [sandbox]> 
MariaDB [sandbox]> 
MariaDB [sandbox]> select * from transport_cms_page; 
+------+------+---------+ 
| id | url | site_id | 
+------+------+---------+ 
| 1 | aaa |  1 | 
+------+------+---------+ 
1 row in set (0.00 sec) 
相關問題