为什么要添加额外的一层SELECT来解决Mysql错误代码:1235

时间:2018-08-17 07:34:54

标签: mysql mysql-workbench

在上一个问题中,我已经问过解决
mysql 1235 错误的解决方案:

  

错误代码:1235。此版本的MySQL尚不支持'LIMIT&   IN / ALL / ANY / SOME子查询”

以下将引发1235

 DELETE
    FROM job_detail_history
    where id not in (select id from job_detail_history order by start_time desc limit 2);

为此,我得到了@Zaynul Abadin Tuhin提供的解决方案 如下,它也对我有用。他只是在我的子查询上添加了一个选择层。并且据他介绍,这是一些mysql专家建议的。
解决上述问题的方法

 DELETE
    FROM job_detail_history
    where id not in (select * from
        (select id from job_detail_history order by start_time desc limit 2) as t1 );


我尝试对数据库表进行分析,发现使用
问题 ::如上所述,这不适用于删除。

select id from job_detail_history order by start_time desc limit 2;

它给我类似的东西:
enter image description here

最后一个null用于工作台建议的新行:

当我添加select的额外一层时:
添加额外的子查询层:这将与我的删除一起使用。

(select id from (select id from job_detail_history order by start_time desc limit 2)  as t1);

它返回如下内容:
enter image description here

所以,我想了解的内容
如何在子查询中多一层解决1235错误?

任何人都可以详细阐述它。

1 个答案:

答案 0 :(得分:1)

subqueryderived table之间存在重要区别。

派生表替换了一个表(用于表,也可以使用“正常”表名),特别是在from <tablename>join <tablename>中,它需要一个别名(或“表名”,就像其他表格一样)。您不能写where not in (<tablename>);那不是派生表,而是子查询。

通常,此问题(以及使用另一层的解决方案)发生在delete

  

您不能从表中删除并在子查询中从同一表中选择。

但是,禁止使用该表的派生表。 MySQL根本无法处理(或不想处理)这种内部依赖性(并根据其规则)的依赖关系。

对于LIMIT,有一个类似的subquery-specific restriction

  

对于某些子查询运算符,MySQL不支持子查询中的LIMIT

     

错误1235(42000):此版本的MySQL尚不支持    “ LIMIT&IN / ALL / ANY / SOME子查询”

对于MySQL有所不同的原因:派生表独立存在,不能依赖外部查询。它可以像普通表一样在内部使用。 (例如,MySQL可以在执行计划的第一步中简单地创建此表,并且该表用于所有其他步骤。)另一方面,子查询可以依赖于外部表(使其成为从属子查询)。

具体地说,

 where id not in (select id from job_detail_history);

相同
 where not exists (select id from job_detail_history sub where sub.id = outer.id);

虽然您无法为limit执行此操作:

 where id not in (select id from job_detail_history limit 2);

不同

 where not exists (select id from job_detail_history sub 
                   where sub.id = outer.id limit 2);

MySQL不能简单地处理此问题,因为它通常用于完成此转换。也许迟早会允许它。为了使它适用于删除,您仍然需要使用子查询。