MySQL:删除子查询返回的行
Posted
技术标签:
【中文标题】MySQL:删除子查询返回的行【英文标题】:MySQL: delete rows returned by subquery 【发布时间】:2012-09-12 08:31:53 【问题描述】:我需要从表中删除重复 link
列的行。我正在尝试运行:
delete from resultitem
where id in (select r.id
from resultitem r
group by r.link
having count(r.id) >1);
但出现错误:
ERROR 1093 (HY000): You can't specify target table 'resultitem' for update in FROM clause
这是否可以在没有临时表的情况下通过 mysql 中的子查询删除行? 请指教。
【问题讨论】:
您似乎试图删除所有重复的条目,而不仅仅是重复的条目。这是你的意图吗? @podiluska 是的,完全正确 【参考方案1】:这应该删除除最低 id
每 link
之外的所有内容:
delete ri1
from resultitem as ri1
inner join
resultitem as ri2
on ri1.link = ri2.link
and ri1.id > ri2.id
Live example at SQL Fiddle.
要删除所有重复链接,不留下任何重复链接,请删除and ri1.id > ri2.id
。
【讨论】:
同样的问题:不能在 FROM 子句中指定目标表 'r1' 进行更新 MySQL 语法总是令人惊讶。编辑后的版本应该可以工作,并在 SQL Fiddle 上进行了测试。【参考方案2】:DELETE resultitem
FROM resultitem
LEFT OUTER JOIN (
SELECT MIN(id) as RowId, link
FROM resultitem
GROUP BY link
) as KeepRows ON
resultitem.id = KeepRows.RowId
WHERE
KeepRows.RowId IS NULL
【讨论】:
【参考方案3】:试试这个...
delete r from resultitem r
INNER JOIN (
(select id
from resultitem rr
group by rr.link
having count(rr.id) >1) rr
ON r.id = rr.id;
【讨论】:
错误:您的 SQL 语法有错误;查看与您的 MySQL 服务器版本相对应的手册,了解在 'ON r.id = rr.id' 附近使用的正确语法【参考方案4】:delete from resultitem
where id not in (select r.id
from (select r1.id, unique(r1.link) from resultitem r1) as r );
【讨论】:
语法错误:ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'unique(r.link) from resultitem r )' at line 1
以上是关于MySQL:删除子查询返回的行的主要内容,如果未能解决你的问题,请参考以下文章