UNION All,Group BY然后获得整体COUNT

时间:2014-01-28 03:59:50

标签: mysql sql mysqli group-by union

我有2张桌子..

用户1

user_id     mobile_no
   1          1111
   2          2222

用户2

user_id     mobile_no
   1          3333
   2          2222

我想首先UNION这些表,然后分组然后想要计算总记录

我正在使用此查询,但它无效

SELECT COUNT(Q2.total) AS Overall
FROM (
   SELECT COUNT(Q.user_id) AS total
   FROM (
     SELECT * FROM user1
     UNION ALL 
     SELECT * FROM user2
   ) Q
  GROUP BY Q.mobile_no
) Q2

如果我使用内部查询e-g:

   SELECT COUNT(Q.user_id) AS total
   FROM (
     SELECT * FROM user1
     UNION ALL 
     SELECT * FROM user2
   ) Q
  GROUP BY Q.mobile_no

我得到了这些结果,实际上我想再次统计这些结果......

total
 2
 1
 1

我期待这个结果

Overall
   3

5 个答案:

答案 0 :(得分:3)

这很奇怪。似乎没有人意识到这很简单:

select count(*) overall
from (select mobile_no from user1 union select mobile_no from user2)

unionunion all之间的区别在于union删除了重复项。

答案 1 :(得分:0)

select count (distinct mobile_no) from
(select user_id, mobile_no from user1 u1
UNION ALL
select user_id, mobile_no from user2 u2
) X
group by X.mobile_no

答案 2 :(得分:0)

而是使用UNION and not UNION ALL

SQL UNION Operator

  

UNION运算符默认情况下仅选择不同的值。允许   重复值,使用UNION的ALL关键字。

SELECT  COUNT(mobile_no) Overall
FROM    (
            SELECT  
                    mobile_no
            FROM    User1
            UNION
            SELECT  
                    mobile_no
            FROM    User2
        ) Q

修改

正如@Bohemian所说,不需要明确的。

答案 3 :(得分:0)

假设您正在寻找不同数量的手机号码:

select count(distinct mobile_no) as Overall
from (
  select user_id, mobile_no
  from user1
  union all
  select user_id, mobile_no
  from user2
) a

答案 4 :(得分:0)

试试这个:

SELECT COUNT(*) FROM 
   ( (SELECT * FROM user1) UNION 
      (SELECT user_id as u1,mobile_no as m1
      FROM user2) )  as a1  GROUP BY a1 .1