Select multiple counts, in multiple tables, in one SQL query

Discuss coding issues, and scripts related to PHP and MySQL.
Admin
Site Admin
Posts: 602

Select multiple counts, in multiple tables, in one SQL query

- If you want to do multiple COUNT(), in multiple tables, and output them in a single SELECT statement with each COUNT being a column; you can use a SQL query like this:

Code: Select all

SELECT
  (SELECT COUNT(*) FROM table_1 WHERE some_condition) AS nrc1,
  (SELECT COUNT(*) FROM table_1 WHERE other_condition) AS nrc2,
  (SELECT COUNT(*) FROM table_2 WHERE some_condition) AS nrc3
FROM table_1 LIMIT 1
- Outputs:

Code: Select all

nrc1 | nrc2 | nrc3
 123 |  78  | 589

Similar Topics