将两个不相关的查询的结果合并到单个视图中

时间:2014-05-16 17:07:04

标签: mysql sql sql-view

是否可以将两个单独(不相关)的sql查询的结果合并到一个视图中。我试图为用户总计一些数字,并计算本月视频的观看次数,以显示在仪表板上。

即,

select count(*) from video where monthname(views) = 'May';

select sum(sessions) from user where user_id = 6;

我想创建一个包含这两个结果的视图。

这可能吗?

2 个答案:

答案 0 :(得分:7)

如果您希望结果在不同的列中彼此相邻,则只需SELECT一个查询列表:

SELECT ( select count(*) from video where monthname(views) = 'May') AS May_CT
      ,( select sum(sessions) from user where user_id = 6) AS User_Sum

如果您希望将结果堆叠在一列中:

select count(*) from video where monthname(views) = 'May'
UNION  ALL
select sum(sessions) from user where user_id = 6

后者可能需要数据类型转换

答案 1 :(得分:5)

SELECT t2.total_session,
       t1.watch_count
FROM
  (SELECT 1 AS common_key,
          count(*) AS watch_count
   FROM video
   WHERE monthname(views) = 'May') AS t1
JOIN
  (SELECT 1 AS common_key,
               sum(sessions) AS total_session
   FROM USER
   WHERE user_id = 6) AS t2 ON t1.common_key = t2.common_key;

当然,只有当t1和t2的输出都是一行时,这才会非常有效。