从另一个select查询中的2个表中进行2个SQL select查询

时间:2012-10-25 12:38:53

标签: sql select merge

我有2个SQL表:"episode""topic",每个主题和剧集都有一个视频(一集包含几个主题,但对我的问题并不重要)。它们有自己的字段,但共有"title", "date", "video_url""count"(计数是观看视频的次数)。

我想根据只有一个查询的计数字段进行前5选择。

所以我需要合并查询:

select title, date, video_url, count from episode order by count desc 

与“来自主题”的查询相同。

1 个答案:

答案 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