Home >Database >Mysql Tutorial >How Can I Combine COUNT(*) Results from Multiple Tables into a Single Row?

How Can I Combine COUNT(*) Results from Multiple Tables into a Single Row?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-11 13:41:41125browse

How Can I Combine COUNT(*) Results from Multiple Tables into a Single Row?

*Merge Count() results from multiple tables into a single row**

To get the count of single row results from multiple tables, for example:

<code>Count_1   Count_2
123       456</code>

Where tab1 and tab2 are source tables, please use the query in the following format:

<code class="language-sql">SELECT  (
        SELECT COUNT(*)
        FROM   tab1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   tab2
        ) AS count2
FROM    dual;</code>

Instructions:

  • The outer SELECT statement acts as a placeholder for returning multiple count results to a single row.
  • The inner SELECT statement calculates the count for each table.
  • dual is a built-in table that contains a single row and is used here as a virtual table. Including it ensures that the outer SELECT statement always returns a single row, even if the source table is empty.
  • Each count result is assigned an alias (count1 and count2) to identify them in the final result.

The above is the detailed content of How Can I Combine COUNT(*) Results from Multiple Tables into a Single Row?. 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