sql合并两个查询结果

时间:2019-03-18 15:45:43

标签: mysql sql

使用xampp mysql
q1:

SELECT truckid, count(deliveryid) 
  FROM `delivery` 
 WHERE year(deliverydate)=2019 and month(deliverydate)=1 
 GROUP BY truckid

q2:

 SELECT truckid,count(deliverid) 
   FROM `delivery2` 
  WHERE YEAR(ddate)=2019 and MONTH(ddate)=1 
  GROUP BY truckid

我正在尝试获得一页带有4列的结果,以便让我在它们之间进行比较

我上个月已经做完了,我想我使用了左联接,但是我现在似乎无法使它起作用:(

帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用union all并进行条件聚合:

select truckid, 
       sum( tbl = 'delivery' ) as delivery_count,
       sum( tbl = 'delivery2' ) as delivery2_count
from (select truckid, deliveryid, 'delivery' as tbl
      from delivery
      where year(deliverydate) = 2019 and month(deliverydate) = 1
      union all
      select truckid, deliverid, 'delivery2'
      from delivery2
      where YEAR(ddate) = 2019 and MONTH(ddate) = 1
     ) t
group by truckid;

答案 1 :(得分:0)

您可以通过UNION-LEFT JOINRIGHT JOIN来模拟with a (truckid, cnt) as ( -- query #1 SELECT truckid, count(deliveryid) FROM delivery WHERE year(deliverydate) = 2019 and month(deliverydate) = 1 group by truckid ), b (truckid, cnt) as ( -- query #2 SELECT truckid, count(deliverid) FROM delivery2 WHERE YEAR(ddate) = 2019 and MONTH(ddate) = 1 GROUP BY truckid ) select -- now the full outer join from a.truck_id, a.cnt as a_cnt, b.cnt as b_cnt left join b on a.truck_id = b.truck_id union select from b.truck_id, a.cnt as a_cnt, b.cnt as b_cnt right join b on a.truck_id = b.truck_id ,如下所示:

{{1}}

答案 2 :(得分:0)

我会这样写:

select truckid, max(delivery1) as delivery1, max(delivery2) as delivery2
from ((select truckid, count(*) as delivery1, 0 as delivery2
       from delivery
       where deliverydate >= '2019-01-01' and deliverydate < '2019-01-02'
       group by truckid
      )
      union all
      (select truckid, 0, count(*) as delivery2
       from delivery2
       where deliverydate >= '2019-01-01' and deliverydate < '2019-01-02'
       group by truckid
      )
     ) t
group by truckid;

我认为这是最有效的方法。

首先,日期范围允许使用索引。

第二,各个表上的group by位于较小的数据上。 GROUP BY的缩放比例要比线性缩放的比例差,因此较小的比例更好。

UNION ALL的数据也较小。

为方便起见,不需要直接使用条件逻辑。