我需要使用相同的查询从所有表中提取数据,并将其分组为一个属性。
我知道如何为一个表执行此操作,但我想将结果合并到一个查询中,然后将输出转储到文件中。
以下是我的示例查询:
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from feb
where type='gen' group by duration
into outfile "/feb";
由于我正在为持续时间属性对此进行分组,因此我最终得到4个不同的输出文件,然后明确地合并和排序数据是我想要避免的。
任何帮助将不胜感激!
欧麦
答案 0 :(得分:3)
您可以使用UNION
:
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from feb
where type='gen' group by duration
UNION
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from apr
where type='gen' group by duration
UNION
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from oct
where type='gen' group by duration
UNION
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from dec
where type='gen' group by duration
into outfile "/all";
请注意,您只在最后使用INFO OUTFILE
子句而不是每个SELECT
语句。
答案 1 :(得分:2)
使用UNION ALL。它提供了比UNION更好的性能,无论如何在这种情况下删除重复都是错误的。您还可以在将所有表放在一起后执行GROUP BY,以便可以跨表对行进行分组。这将为您提供所有4个表中相同持续时间的行计数。
select everything.duration, count(*)
from
((select TIMESTAMPDIFF(hour,startTime,endTime) as duration
from feb where type='gen')
union all
(select TIMESTAMPDIFF(hour,startTime,endTime) as duration
from apr where type='gen')
union all
(select TIMESTAMPDIFF(hour,startTime,endTime) as duration
from oct where type='gen')
union all
(select TIMESTAMPDIFF(hour,startTime,endTime) as duration
from dec where type='gen')) everything
group by everything.duration
into outfile "/all";