sql - 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 子查询”
解决方案
您正在使用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
在标量子查询中是允许的。
推荐阅读
- identityserver4 - 带有 Google 登录按钮的身份服务器 4
- python - PySCIPOpt 中的指示变量
- c# - 试图在mvc的proc中获取键值传递
- java - 从 FTP 客户端读取多个文件时出现 java.io.IOException
- c - 删除自平衡二叉搜索树中的节点时出现内存错误/泄漏 - 如何释放其内存?
- amazon-web-services - 为 AWS EC2 用户数据脚本传递 API 密钥的最佳方法是什么
- flutter - 如何在颤动中创建浮动按钮栏?
- python - Pycharm 主题 - 没有 python 彩色语法
- ios - Xcode 11:使用聚合的 swift 框架构建失败
- java - 我想全局捕获所有可能的android异常,因此应用程序无法关闭