MySQL使用子查询删除行

时间:2013-11-21 11:05:20

标签: mysql subquery delete-row

我想从链接表中删除重复的行。这里的选择查询确实有效:

SELECT *
from LINKS t1
WHERE EXISTS (
    SELECT *
    from LINKS t2
    where t2.cntid = t1.cntid
        and t2.title= t1.title
        and t2.lnkid > t1.lnkid
);

当我将同一个查询更改为删除时:

    DELETE from LINKS t1
WHERE EXISTS (
    SELECT *
    from LINKS t2
    where t2.cntid = t1.cntid
        and t2.title= t1.title
        and t2.lnkid > t1.lnkid
);

它不再起作用并指出:ERROR 1064(42000):您的SQL语法出错

这是什么问题?有人可以帮忙解决问题吗?

2 个答案:

答案 0 :(得分:2)

您只能使用JOIN而不使用EXISTS和内嵌视图执行此操作,如下所示:

DELETE t1
FROM LINKS t1, LINKS t2
WHERE t2.cntid = t1.cntid
    AND t2.title= t1.title
    AND t2.lnkid > t1.lnkid

这比使用EXISTS更快。当然,你可以像这样转换SELECT。

SELECT *
from LINKS t1, LINKS t2
WHERE t2.cntid = t1.cntid
    AND t2.title= t1.title
    AND t2.lnkid > t1.lnkid

如果您尝试删除,请set autocommit = '0'

答案 1 :(得分:1)

尝试:

DELETE t1 from LINKS t1 
   WHERE EXISTS (SELECT * from (select * from LINKS) t2 
                   where t2.cntid = t1.cntid 
                   and t2.title= t1.title 
                   and t2.lnkid > t1.lnkid);

SQLFiddle demo