首页 > 解决方案 > where column in from another select results with limit (mysql/mariadb)

问题描述

当我运行此查询时,将返回其 id 存在于从 table2 中选择的所有行

SELECT * FROM table1 WHERE id in (
    SELECT id FROM table2 where name ='aaa'
)

但是当我将限制或之间添加到第二个选择时:

SELECT * FROM table1 WHERE id in (
    SELECT id FROM table2 where name ='aaa' limit 4
)

返回此错误:

此版本的 MariaDB 尚不支持“LIMIT & IN/ALL/ANY/SOME 子查询”

标签: sqlmariadbmariadb-10.3

解决方案


您正在使用LIMIT没有ORDER BY. 通常不建议这样做,因为这会返回任意一组行——并且这些行可能会从一个执行更改为另一个执行。

您可以将其转换为JOIN-- 幸运的是。如果id在 中不重复table2

SELECT t1.*
FROM table1 t1 JOIN
     (SELECT t2.id
      FROM table2 t2
      WHERE t2.name = 'aaa' 
      LIMIT 4
     ) t2
     USING (id);

如果id可以在 中复制table2,则:

SELECT t1.*
FROM table1 t1 JOIN
     (SELECT DISTINCT t2.id
      FROM table2 t2
      WHERE t2.name = 'aaa' 
      LIMIT 4
     ) t2
     USING (id);

另一种有趣的方式使用LIMIT

SELECT t1.*
FROM table1 t1
WHERE id <= ANY (SELECT t2.id
                 FROM table2 
                 WHERE t2.name = 'aaa'
                 ORDER BY t2.id
                 LIMIT 1 OFFSET 3
                );

LIMIT 在标量子查询中是允许的。


推荐阅读