如何合计3个select语句计数?

gdx19jrr  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(432)

我有三个select语句如下,我想总结一下记录的总数。我该怎么做?

SELECT COUNT(*) AS Number FROM tableA where user_id = 5   //Total 5 records
SELECT COUNT(*) AS Number FROM tableB where user_id = 5   //Total 6 records
SELECT COUNT(*) AS Number FROM tableC where user_id = 5   //Total 1 records

所以返回结果是12。

ecfdbz9o

ecfdbz9o1#

你可以申请 count(*) 结果是 union all :

SELECT COUNT(*)
FROM   (SELECT user_id FROM tablea
        UNION ALL
        SELECT user_id FROM tableb
        UNION ALL
        SELECT user_id FROM tablec) t
WHERE  user_id = 5
6vl6ewon

6vl6ewon2#

select ( select count(*) from tableA where user_id = 5 )
     + ( select count(*) from tableB where user_id = 5 ) 
     + ( select count(*) from tableC where user_id = 5 ) 
     as total_rows
from dual
lawou6xi

lawou6xi3#

我认为这应该起作用:

SELECT SUM(Number)
FROM (
    SELECT COUNT(*) AS Number FROM tableA where user_id = 5
    UNION ALL
    SELECT COUNT(*) AS Number FROM tableB where user_id = 5
    UNION ALL
    SELECT COUNT(*) AS Number FROM tableC where user_id = 5
)

相关问题