DatabaseDatabase·

COUNT(*) from multiple tables in MySQL

Published at 2024-08-18 18:55:05Viewed 77 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.

弦圈热门内容

Python pip安装SSL证书错误

问题描述:正常使用pip install xxx安装会弹出错误,导致下载失败。必须增加trust host字段,才能下载成功:pip --trusted-host pypi.python.org install在cmd运行python -c "import ssl; print(ssl.get_default_verify_paths())"在默认路径里没有找到ca证书,而在Lib\site-packages\certifi文件夹中,却发现了cacert.pem文件。故而认为原因是ca证书丢失或者寻找ca证书路径出错,因此尝试修改pip的默认ca证书路径。pip.ini文件中有大量的pip配置信息,因此需要先找到该文件。在cmd通过pip -v config list发现,在多个路径中,都没有找到pip.ini文件。且了解到,pip会有一个默认的pip.conf文件(其实就是pip.ini),因此断定默认pip.ini配置文件丢失。解决办法:在python根目录中,新建pip.ini,在里面写上[global] index-url = https://mirrors.aliyun.co ...

pyttsx3运行错误

接上文Python实现语音朗读,运行示例代码时import pyttsx3 engine = pyttsx3.init() engine.say('开车不规范,亲人两行泪,I love China') engine.runAndWait()弹出以下错误:经过检查,pywin32等库都已经安装好了。尝试使用win32com库替代pyttsx3,结果仍然报错,报错内容为win32 api。之后又尝试了几种办法,仍然都是跟win32有关的报错。因为之前pip安装总是SSL报错,刚开始以为是SSL报错导致安装出错。但是修复SSL报错问题后(见Python pip安装SSL证书错误),该问题仍然没解决。最后经过了解,可能是pywin32版本过高所导致。一般需要将pywin32版本控制在305以下,可以使用225或者226这样的低版本。于是使用pip下载对应版本pip install pypiwin32 pip install pywin32 == 225然而,下载时发现已经没有225版本可以下载。因此另寻办法。最终,发现是pywin32安装的版本有问题,导致包虽然有了,但是却无法识别,导致出现N ...

Get connected with us on social networks! Twitter

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