我可以有条件地运行连续的 MySQL 子查询吗?
我目前有 PHP 代码,它运行一个带有子查询的复杂查询,希望找到 12 个匹配的记录。如果返回的记录少于 12 条,代码将运行同一查询的第二个版本,并稍微修改一下 WHERE 子句,以添加到第一个查询先前检索到的记录中。它继续运行查询的修改版本,直到组装完总共 12 条记录。
我知道我可以将多个查询(目前有五个)与 UNION 组合起来,但是即使联合中的第一个查询成功返回 12 条记录,所有查询也会运行。由于每个查询都很复杂,我不想浪费资源。 (或者,我错了吗?一旦达到 LIMIT,MySQL 是否知道停止执行子查询?)
MySQL 有没有办法完成我目前在 PHP 中所做的事情?例如,如何才能拥有一个包含五个子查询的查询,并且仅当前面的子查询未产生所需的计数时才继续执行连续的子查询?
I currently have PHP code that runs a single complex query, with subqueries, in hopes of finding 12 matching records. If less than 12 records are returned, the code runs a second version of the same query, with a slightly modified WHERE clause, to add to the records previously retrieved by the first query. It continues running modified versions of the query until a grand total of 12 records are assembled.
I know that I could combine the multiple queries -- there are currently five -- with a UNION, but then all of the queries get run even if the first query in the union is successful in returning 12 records. Since each query is complex, I don't want to waste the resources. (Or, am I wrong about that? Does MySQL know to stop executing subqueries once a LIMIT is reached?)
Is there a way in MySQL to accomplish what I'm currently doing in PHP? For instance, how can I have a query with five subqueries, and progress through successive subqueries only if the preceding subqueries don't produce a desired count?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个 存储过程< /a> 在服务器上执行此检查非常简单。
You can create a stored procedure on the server that does this check quite simply.