Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT(*) from multiple tables in MySQL

Tags:

mysql

count

How do I go about selecting COUNT(*)s from multiple tables in MySQL?

Such as:

SELECT COUNT(*) AS table1Count FROM table1 WHERE someCondition JOIN??  SELECT COUNT(*) AS table2Count FROM table2 WHERE someCondition CROSS JOIN? subqueries? SELECT COUNT(*) AS table3Count FROM table3 WHERE someCondition 

Edit:

The goal is to return this:

+-------------+-------------+-------------+ | table1Count | table2Count | table3Count | +-------------+-------------+-------------+ | 14          | 27          | 0           | +-------------+-------------+-------------+ 
like image 924
bcmcfc Avatar asked Sep 21 '10 14:09

bcmcfc


People also ask

What is count (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.

Can you SELECT from multiple tables in MySQL?

You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table. You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables.

What does SELECT count (*) from table do?

SQL SELECT COUNT(*) function The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).


2 Answers

You can do it by using subqueries, one subquery for each tableCount :

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 
like image 75
Julien Hoarau Avatar answered Sep 24 '22 08:09

Julien Hoarau


You can do this with subqueries, e.g.:

select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count,         (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count  
like image 35
D'Arcy Rittich Avatar answered Sep 24 '22 08:09

D'Arcy Rittich