Combine results of two unrelated queries into single view

回眸只為那壹抹淺笑 提交于 2019-11-30 15:36:22
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;

Ofcourse, this will be very efficient only when the output in both t1 and t2 is one row.

If you want the results next to each other in separate columns you can simply SELECT a list of queries:

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

If you want the results stacked in one column:

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

The latter may require datatype conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!