为什么不删除条目?

时间:2017-05-12 04:12:17

标签: mysql sql

为什么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);

2 个答案:

答案 0 :(得分: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以外的字段。

答案 1 :(得分: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)
相关问题