Mysql Query从多个表

时间:2018-06-08 11:04:26

标签: mysql

我有三个表movie_requestmovie_request_2movie_request_3我希望从每个表中获取计数()并返回一行,每个表计数()作为专栏。

movie_request是free_cnt, movie_request_2是plus_cnt, movie_request_3是visitor_cnt

我希望结果如

movie_id | movie_title | free_cnt | plus_cnt | visitor_cnt
   10    |   Test      |    5     |    10    |    15
   11    |   Test2     |    6     |    11    |    25

这是我的查询

SELECT movie_title,movie_id,MAX(x.free_cnt) as free_cnt, MAX(x.plus_cnt) as plus_cnt, MAX(x.visitor_cnt) as visitor_cnt, (MAX(x.free_cnt) + MAX(x.plus_cnt) + MAX(x.visitor_cnt)) AS total
        FROM (
            SELECT a1.id as movie_id, a1.movie_title as movie_title, 0 as plus_cnt, 0 as visitor_cnt, COUNT(*) AS free_cnt
            FROM movie_request a1
            GROUP BY a1.movie_title
            UNION ALL

            SELECT a2.id as movie_id, a2.movie_title as movie_title,  0 as free_cnt, 0 as visitor_cnt, COUNT(*) AS plus_cnt
            FROM movie_request_2 a2
            GROUP BY a2.movie_title
            UNION ALL

            SELECT a3.id as movie_id, a3.movie_title as movie_title,  0 as plus_cnt, 0 as free_cnt,  COUNT(*) AS visitor_cnt
            FROM movie_request_3 a3
            GROUP BY a3.movie_title
        ) AS x
        GROUP BY movie_title

我不断得到这样的结果

 movie_id | movie_title | free_cnt | plus_cnt | visitor_cnt
       10    |   Test      |    5     |    0    |    0
       11    |   Test2     |    6     |    0    |    0

我已经测试了结果,他们都返回了结果。

我如何解决?

3 个答案:

答案 0 :(得分:1)

在各种选择中,保持相同的列顺序 所以

SELECT   a1.id as movie_id,
         a1.movie_title as movie_title,
         COUNT(*) AS free_cnt
         0 as plus_cnt,
         0 as visitor_cnt
FROM     movie_request a1
GROUP BY a1.movie_title

UNION ALL

SELECT   a2.id as movie_id,
         a2.movie_title as movie_title,
         0 as free_cnt,
         COUNT(*) AS plus_cnt,
         0 as visitor_cnt
FROM     movie_request_2 a2
GROUP BY a2.movie_title

UNION ALL

SELECT   a3.id as movie_id,
         a3.movie_title as movie_title,
         0 as plus_cnt,
         0 as free_cnt,
         COUNT(*) AS visitor_cnt
FROM     movie_request_3 a3
GROUP BY a3.movie_title

答案 1 :(得分:1)

我通过参考以下链接获得了解决方案

https://stackoverflow.com/questions/3761240/count-from-multiple-tables-in-mysql

答案 2 :(得分:0)

一种选择是将三个表与计算列结合在一起。然后,使用条件聚合并转出所需的计数:

SELECT
    t.movie_id,
    t.movie_title,
    COUNT(CASE WHEN t.label = 'free'    THEN 1 END) AS free_cnt,
    COUNT(CASE WHEN t.label = 'plus'.   THEN 1 END) AS plus_cnt,
    COUNT(CASE WHEN t.label = 'visitor' THEN 1 END) AS visitor_cnt
FROM
(
    SELECT movie_id, movie_title, 'free' AS label
    FROM movie_request
    UNION ALL
    SELECT movie_id, movie_title, 'plus'
    FROM movie_request_2
    UNION ALL
    SELECT movie_id, movie_title, 'visitor'
    FROM movie_request_3
) t
GROUP BY
    t.movie_id, t.movie_title;

顺便说一句,您的架构设计确实留下了一些需要的东西。您通常不应该为简单的报告问题编写这样丑陋的查询。最有可能的是,你应该只有一个电影请求表,可能还有我必须在上面生成的计算列。