我可以有条件地运行连续的 MySQL 子查询吗?

发布于 2024-10-04 03:35:42 字数 370 浏览 5 评论 0原文

我目前有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼中杀气 2024-10-11 03:35:42

You can create a stored procedure on the server that does this check quite simply.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文