Home >Database >Mysql Tutorial >How to Combine Multiple SELECT Statements with LIMIT 1 in SQL?

How to Combine Multiple SELECT Statements with LIMIT 1 in SQL?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 12:52:11607browse

How to Combine Multiple SELECT Statements with LIMIT 1 in SQL?

Combining Multiple SELECT Statements

As you've mentioned, you're facing an issue when attempting to combine multiple SELECT statements that each limit the results to a single row. The challenge arises when using UNION ALL because the LIMIT clause seems to disrupt the union process.

To resolve this, you can employ parentheses to enclose each individual SELECT statement. This ensures the union is performed correctly, as the documentation for UNION explicitly states that ORDER BY and LIMIT clauses must be enclosed within parentheses to apply to the subexpression rather than the result of the union.

Here's how you can modify your query:

(SELECT result FROM foo.table LIMIT 1)
UNION ALL
(SELECT result FROM bar.table LIMIT 1)
UNION ALL
(SELECT result FROM doo.table LIMIT 1)

This syntax ensures that each sub-statement is processed separately, with the LIMIT clause applied to the individual results. The union is then performed on the individual row results, giving you a single column with the expected number of rows to match the schema names.

The above is the detailed content of How to Combine Multiple SELECT Statements with LIMIT 1 in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn