tags:

views:

120

answers:

4

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           |
+-------------+-------------+-------------+
A: 

You can use UNION

  SELECT COUNT(*) FROM table1 WHERE someCondition
  UNION
  SELECT COUNT(*) FROM table2 WHERE someCondition
  UNION
  SELECT COUNT(*) FROM table3 WHERE someCondition
Interfector
Union will give the results in individual rows instead of columns. The resultset the OP is looking for is a single row with 3 count columns
Brendan Bullen
+5  A: 

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
madgnome
+2  A: 

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 
RedFilter
+1  A: 

Try Changing to

SELECT 
    COUNT(table1.*) as t1,
    COUNT(table2.*) as t2,
    COUNT(table3.*) as t3 
FROM table1 
    LEFT JOIN tabel2 ON condition
    LEFT JOIN tabel3 ON condition
JapanPro