2012-11-03 60 views
0

我有一個結果作爲加入不同行和多個SELECT語句兩個表

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; 

現在我得到100行和正確的價值觀的名稱和date_registered但我正在逐漸爲NULL爲EmaxViews所有的行..

什麼是錯我的查詢?

+0

你能給我們從你正在尋找從中讀取數據的表格樣本? – Codeguy007

回答

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 
+0

不..我很抱歉..我在第二個查詢中給出了錯誤的列名..我解決了它..謝謝 – ILuvProgramming

0

沒有..我抱歉..我在第二個查詢給錯列名..我解決了它..感謝