MySQL将2个表合并为1个,而不是将其与另一个表

时间:2016-02-07 08:30:18

标签: mysql

我有2张桌子(标题和剧集)。

   Table Titles

   id |  title  |  type  | views
   ------------------------------
   1  |  Lucy   | movie  | 300
   2  |  Narcos | series | 2600
   3  | Ip Man  | movie  | 120
   4  |  Creed  | movie  | 460


   Table Episodes

   id |  title_id  |   title  |  episode | views
   ----------------------------------------------
   1  |      2     | episode1 |     1    | 100
   2  |      2     | episode2 |     2    | 260
   3  |      2     | episode3 |     3    | 96
   4  |      2     | episode4 |     4    | 210

现在我使用此查询来获取观看次数最多的剧集。

SELECT titles.id, titles.title, episodes.title_id, episodes.episode, episodes.views FROM titles, episodes WHERE titles.id = episodes.title_id ORDER BY episodes.views DESC LIMIT 0, 16

我将此查询用于电影。

SELECT titles.id, titles.title, titles.views WHERE type = 'movie' ORDER BY titles.views DESC LIMIT 0, 16

我想将这两个最后的查询合并到一个临时表中,以显示观看次数最多的电影和剧集。

   Temporary Table

   id |  title_id  |        title      |   views
   ----------------------------------------------
   1  |      4     |       Creed       |   460 
   2  |      1     |       Lucy        |   300  
   3  |      2     |  Narcos Episode 2 |   260  
   4  |      2     |  Narcos Episode 4 |   210  

我该怎么做?

谢谢。

2 个答案:

答案 0 :(得分:0)

你可以使用视图 请参阅此页面以获取更多信息 http://dev.mysql.com/doc/refman/5.7/en/create-view.html

答案 1 :(得分:0)

我明白了,谢谢@sagi

  (SELECT titles.id as title_id, concat(titles.title,' ',episodes.title) as                          
  title,episodes.views as views
  FROM titles, episodes 
  WHERE titles.id = episodes.title_id and type = 'series'
  ORDER BY episodes.views DESC LIMIT 0, 16) 
  UNION ALL
  (SELECT titles.id, titles.title, titles.views as views
  FROM titles
  WHERE type = 'movie'
  ORDER BY titles.views DESC LIMIT 0, 16) ORDER BY views DESC