【问题标题】:How to delete records in DB with mySQL using group by [duplicate]如何使用 group by [重复] 使用 mySQL 删除数据库中的记录
【发布时间】:2011-10-09 12:08:13
【问题描述】:

可能重复:
SQL Delete: can't specify target table for update in FROM clause

我只有一张表(将此表称为 TAB),代表大学考试。我有以下属性:CourseName、CourseCode 和 year。我想删除所有基数小于 100 的课程。如果我输入

select CourseName from TAB group by CourseName having count(CourseName) < 100;

我有一个确切的结果。但是,如果我想删除这些条目,我会尝试使用

delete from TAB where CourseName not in (select CourseName from TAB group by CourseName having count(CourseName) > 100);

但是系统返回错误:

错误代码:1093 您不能在 FROM 子句中指定目标表 'TAB' 进行更新

我必须如何删除这些记录?

【问题讨论】:

    标签: mysql sql syntax sql-delete


    【解决方案1】:

    也许这可行?

    DELETE FROM tab AS a 
    INNER JOIN (select CourseName from TAB group by CourseName having count(Coursename)>100) as b
    ON a.CourseName = b.coursename
    

    【讨论】:

      【解决方案2】:
        $result=mysql_query("select CourseName from TAB group by CourseName having count(CourseName) < 100");
      while($row=mysql_fetch_array($result)){
      mysql_query("delete from tab where courses='$row[0]'");
      }
      

      【讨论】:

      • 单独删除结果会在 SQL Server 端使用更多带宽和处理能力。它需要下载 Web 服务器不需要的可能数十万行的列表,然后执行十万条额外的 SQL 语句。
      【解决方案3】:

      最简单的方法之一是从您的​​第一个查询创建一个临时表,然后在第二个语句中删除临时表中不存在的所有课程。

      【讨论】:

      • 好的,如何创建临时表?
      【解决方案4】:

      请在以下链接中查看答案。它将解决您的问题:

      基本上,您不能从 SELECT 中使用的同一个表中删除(修改)。该页面记录了一些解决方法。

      通过将嵌套的select 设为临时表,以下操作将起作用。

      delete from TAB
      where CourseName not in (select temp.CourseName
                               from (select t.CourseName
                                     from TAB t
                                     group by t.CourseName
                                     having count(t.CourseName) > 100
                                    ) as temp
                              )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        相关资源
        最近更新 更多