·

COUNT(*) from multiple tables in MySQL

Published at 2024-08-18 18:55:05Viewed 157 times
Professional article
Please reprint with source link

Question

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


Answer 1

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


Answer 2

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 


Answer 3

You can use UNION

  SELECT COUNT(*) FROM table1 WHERE someCondition
  UNION
  SELECT COUNT(*) FROM table2 WHERE someCondition
  UNION
  SELECT COUNT(*) FROM table3 WHERE someCondition


The content is from StackOverflow which is translated and used in accordance with the CCBY-SA 4.0 license agreement. Original link: COUNT(*) from multiple tables in MySQL

Comments

There is no comment, let's add the first one.

弦圈热门内容

[antd: Message] You are calling notice in render which will break in React 18 concurrent mode. Please trigger in effect instead.

I'm getting this error when using MessageWarning: [antd: Message] You are calling notice in render which will break in React 18 concurrent mode. Please trigger in effect instead.Here is my code:import { message } from 'antd'; export default function Page() { const [messageApi, contextHolder] = message.useMessage(); const res = await fetch("/api/...", { method: "POST", }); if (!res.ok) { messageApi.error("Error! Fail to login!"); } return ( <Home> ... </Home> ) }

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved