Home > Database > Mysql Tutorial > How to Retrieve COUNT(*) Values from Multiple Tables in MySQL?

How to Retrieve COUNT(*) Values from Multiple Tables in MySQL?

Patricia Arquette
Release: 2024-11-04 15:04:02
Original
1000 people have browsed it

How to Retrieve COUNT(*) Values from Multiple Tables in MySQL?

Retrieve COUNT(*) Values from Multiple Tables in MySQL

In MySQL, you can retrieve the count of rows from multiple tables using subqueries. Subqueries allow you to execute multiple queries within a single statement.

To select the COUNT(*) for each table, create a subquery for each table, as shown below:

<code class="sql">SELECT
  (SELECT COUNT(*) FROM table1 WHERE someCondition) AS table1Count, 
  (SELECT COUNT(*) FROM table2 WHERE someCondition) AS table2Count,
  (SELECT COUNT(*) FROM table3 WHERE someCondition) AS table3Count</code>
Copy after login

This query performs the following steps:

  1. Executes the first subquery to count the rows in table1 that meet the specified condition.
  2. Executes the second subquery to count the rows in table2 that meet the specified condition.
  3. Executes the third subquery to count the rows in table3 that meet the specified condition.
  4. Combines the results of the subqueries and displays them as columns with the specified aliases (table1Count, table2Count, table3Count).

The output of the query will be a table with three columns, each representing the count of rows from a specific table. For example, the following output shows the count of rows from three tables:

+-------------+-------------+-------------+
| table1Count | table2Count | table3Count |
+-------------+-------------+-------------+
| 14          | 27          | 0           |
+-------------+-------------+-------------+
Copy after login

The above is the detailed content of How to Retrieve COUNT(*) Values from Multiple Tables in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template