我想对同一张表执行合并以将两个不同的结果组合在一起。理想的结果是拥有6条记录,这些记录代表每个区域(在这种情况下为两个区域EWR,LGA)的访问量最高的前3个目的地。 我标记了SQL Server和MySQL,因为我希望查询可以在两个RDBMS上运行。
答案 0 :(得分:4)
对于 MySql :
将您的每个查询括在括号内:
\text{}
对于 Sql Server :
(
select count(flight) as numberOfFlights, origin, dest
from flights
where origin = 'EWR'
group by origin, dest
order by numberOfFlights desc limit 3
)
union all
(
select count(flight) as numberOfFlights, origin, dest
from flights
where origin = 'LGA'
group by origin, dest
order by numberOfFlights desc limit 3
)
答案 1 :(得分:1)
您有两个由union
连接的相同查询。由于union
删除重复项,因此等效于:
select count(*) as numberofflights, origin
from flights
where destination = 'EWR'
group by origin
order by numberofflights desc;
不需要union
。您的版本只会增加不必要的开销。
答案 2 :(得分:1)
在评论后进行编辑。
SELECT *
FROM (SELECT TOP 3 COUNT(*) AS numberofflights, origin, dest
FROM flights
WHERE origin = 'EWR'
GROUP BY origin, dest
UNION
SELECT TOP 3 COUNT(*) AS numberofflights, origin, dest
FROM flights
WHERE origin = 'LGA'
GROUP BY origin, dest
) A
ORDER BY 2,1 desc