连接两个具有不同行和多个select语句的表

时间:2012-11-03 22:05:50

标签: mysql sql database join

我的结果为

select D.name as username, E.maxViews AS EmaxViews from (select A.video_id, A.uploaded_by AS username,max(B.numViews) AS maxViews,count(*) AS C from Videos A, (select video,count(*) AS numViews from Views GROUP BY video) B where A.video_id=B.video GROUP BY A.uploaded_by) E, Users D where D.username=E.username

它为我提供了username,EmaxViews列,并为我提供了93行

我有另一个表Users (username,date_registered,name),其中有100个查询

我想将上述两个查询作为单个表加入

username, date_registered, EmaxViews

我试过这个

select name, date_registered,G.EmaxViews from Users F LEFT OUTER JOIN (select D.name as username, E.maxViews AS EmaxViews from (select A.video_id, A.uploaded_by AS username,max(B.numViews) AS maxViews,count(*) AS C from Videos A, (select video,count(*) AS numViews from Views GROUP BY video) B where A.video_id=B.video GROUP BY A.uploaded_by) E, Users D where D.username=E.username) G ON F.username=G.username ORDER BY F.date_registered;

现在我为name和date_registered获取了100行和正确的值,但是对于所有行,EmaxViews都获得了NULL ..

我的查询中有什么问题?

2 个答案:

答案 0 :(得分:1)

SELECT  u.name AS username,
        u.date_registered,
        COALESCE
                (
                (
                SELECT  COUNT(*) cnt
                FROM    video v
                JOIN    views vw
                ON      vw.video = v.video_id
                WHERE   v.uploaded_by = u.name
                GROUP BY
                        v.video_id
                ORDER BY
                        cnt DESC
                LIMIT 1
                ),
                0
                ) AS EmaxViews
FROM    users u

答案 1 :(得分:0)

不..我很抱歉..我在第二个查询中给出了错误的列名...我解决了..谢谢