MySQL DELETE 使用 Have 和 Count 的子查询
Posted
技术标签:
【中文标题】MySQL DELETE 使用 Have 和 Count 的子查询【英文标题】:MySQL DELETE With a Sub-Query using Having and Count 【发布时间】:2011-06-23 15:18:02 【问题描述】:我正在尝试使用以下查询删除多个条目:
首先,我使用此查询找到要删除的条目:
SELECT guid FROM account GROUP BY guid,type HAVING count(type) > 1);
然后我将此查询添加到 DELETE 语句中:
DELETE FROM account WHERE guid IN (SELECT guid FROM account GROUP BY guid,type HAVING count(type) > 1);
但我得到这个错误:
您不能在 FROM 子句中指定目标表 'account' 进行更新
【问题讨论】:
看这里:***.com/questions/45494/… 【参考方案1】:我认为您需要使用临时表来满足您的需求,如下所示:
第一步:创建临时表
CREATE TEMPORARY TABLE MyTemp
SELECT guid FROM account
GROUP BY guid,type HAVING count(type) > 1;
在你的删除语句中使用临时表
DELETE FROM account
WHERE guid IN (SELECT guid FROM MyTemp);
删除临时表
DROP TEMPORARY TABLE MyTemp;
编辑:我认为使用 *两个嵌套表也可以解决:
DELETE FROM account
WHERE guid IN
(SELECT guid FROM
(SELECT guid FROM account
GROUP BY guid,type HAVING count(type) > 1) as MyTemp
)
【讨论】:
【参考方案2】:你的问题已经解决了,按照下面的操作就行了..
DELETE FROM account
WHERE guid IN
(SELECT * FROM
(SELECT guid FROM account
GROUP BY guid,type
HAVING count(type) > 1) AS a);
【讨论】:
谢谢 Abhik,但您不能从您选择的同一个表中删除。【参考方案3】:首先创建视图
create view view_acct as
SELECT guid FROM account
GROUP BY guid,type HAVING count(type) > 1;
使用后查看
DELETE FROM account WHERE guid in (select * from view_acct);
【讨论】:
以上是关于MySQL DELETE 使用 Have 和 Count 的子查询的主要内容,如果未能解决你的问题,请参考以下文章
Error launching Studio If you already have a 64-bit JDK installed, define a JAVA_HOME variable in Co
cvc-complex-type.2.3:Element ‘filter-mapping‘ cannot have character [children],because the type‘s co
cvc-complex-type.2.3:Element ‘filter-mapping‘ cannot have character [children],because the type‘s co