我有2个SQL表:"episode"
和"topic"
,每个主题和剧集都有一个视频(一集包含几个主题,但对我的问题并不重要)。它们有自己的字段,但共有"title", "date", "video_url"
和"count"
(计数是观看视频的次数)。
我想根据只有一个查询的计数字段进行前5选择。
所以我需要合并查询:
select title, date, video_url, count from episode order by count desc
与“来自主题”的查询相同。
答案 0 :(得分:2)
select top 5 *
from
(
select title, date, video_url, count from episode
union all
select title, date, video_url, count from topic
) as A
order by count desc
您可以添加类型名称以查找其是剧集还是主题。您还可以将top
5添加到子查询中,以便服务器知道他不需要获取所有记录
select top 5 *
from
(
select top 5 title, date, video_url, count, 'episode' as type_name from episode order by count desc
union all
select top 5 title, date, video_url, count, 'topic' as type_name from topic order by count desc
) as A
order by count desc