如何总计3个选择语句计数?

时间:2018-06-09 10:20:43

标签: mysql sql 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。

3 个答案:

答案 0 :(得分:1)

您可以将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

答案 1 :(得分:0)

我认为这应该可以解决问题:

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
)

答案 2 :(得分:0)

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