联合所有两个表但列数不同

时间:2014-07-19 17:42:41

标签: mysql sql

select count(*) as total FROM ( SELECT * FROM database1.orders WHERE number LIKE "11111111111111111" UNION ALL SELECT * FROM database2.orders WHERE number LIKE "11111111111111111" ) AS b

但我收到了错误:

使用的SELECT语句具有不同的列数

因为运行database1给我的结果是null。

如何将其与查询合并,因为查询可帮助我处理分页

感谢帮助!

2 个答案:

答案 0 :(得分:2)

只需在union all之前进行聚合:

select sum(cnt) as total
FROM ((SELECT count(*) as cnt
       FROM database1.orders
       WHERE number LIKE '11111111111111111'
      )
      UNION ALL
      (SELECT count(*) as cnt
       FROM database2.orders
       WHERE number LIKE '11111111111111111'
      )
     ) t;

注意我将字符串分隔符更改为单引号而不是双引号。优良作法是对字符串和日期常量使用单引号(而不是其他任何内容)。

顺便说一句,您也可以使用联接来执行此操作:

select o1.cnt1, o2.cnt1, (o1.cnt1 + o2.cnt1) as total
FROM (SELECT count(*) as cnt1
      FROM database1.orders
      WHERE number LIKE '11111111111111111'
     ) o1 cross join
     (SELECT count(*) as cnt2
      FROM database2.orders
      WHERE number LIKE '11111111111111111'
     ) o2;

这样可以更轻松地获取两个数据库的个别计数。

答案 1 :(得分:2)

ordersdatabase1表的列数可能与database2中同名的列数不同。

不要使用select *,而是选择您感兴趣的列,例如select userid, productid, deliveryaddress, ...。确保在union

的两个部分中指定相同的列

对于count(*),您可以根本不选择任何列,并为每行选择值1,例如:

select  count(*)
from    (
        select  1
        from    database1.orders
        where   number like '111'
        union all
        select  1
        from    database2.orders
        where   number like '111'
        ) as SubQueryAlias

或者您可以在没有union的情况下添加两个子查询的结果:

select  (
        select  count(*)
        from    database1.orders
        where   number like '111'
        )
        +
        (
        select  count(*)
        from    database2.orders
        where   number like '111'
        )