2010-10-08 44 views
0

以下查詢運行良好。它從3個MySQL表中提取信息:登錄,提交和評論。修改聯接查詢以向查詢添加新值

它基於從這三個表中拉出的值計算創建一個名爲totalScore2的值。

的MySQL表「評論」和「提交」都具有以下字段:

loginid submissionid 

在該表「提交」,每個「submissionid」只有一個入口/行,因此只有一個「 loginid「與之相關聯。

在表格「comment」中,字段「submitid」可能有多個條目/行,並可能與多個「loginid」關聯。

每次「評論」中的「submissionid」之一都與表「提交」中的「loginid」相關聯時,我想將其作爲以下等式的一個因子。我想多次像這樣的時間(-10)。

我該怎麼做?

由於提前,

約翰

$sqlStr2 = "SELECT 
    l.loginid, 
    l.username, 
    l.created, 
    DATEDIFF(NOW(), l.created) + COALESCE(s.total, 0) * 5 + COALESCE(scs.total, 0) * 10 + COALESCE(c.total, 0) AS totalScore2 
FROM login l  
LEFT JOIN (
    SELECT loginid, COUNT(1) AS total 
    FROM submission 
    GROUP BY loginid 
) s ON l.loginid = s.loginid 
LEFT JOIN (
    SELECT loginid, COUNT(1) AS total 
    FROM comment 
    GROUP BY loginid 
) c ON l.loginid = c.loginid 
LEFT JOIN (
    SELECT S2.loginid, COUNT(1) AS total 
    FROM submission S2 
    INNER JOIN comment C2 
    ON C2.submissionid = S2.submissionid 
    GROUP BY S2.loginid 
) scs ON scs.loginid = l.loginid 
GROUP BY l.loginid 
ORDER BY totalScore2 DESC 
LIMIT 25"; 
+0

我想通了我自己。見下文。 – John 2010-10-11 09:33:24

回答

0
$sqlStr3 = "SELECT 
     l.loginid, 
     l.username, 
    l.created, 
    DATEDIFF(NOW(), l.created) + COALESCE(s.total, 0) * 5 + COALESCE(scs.total, 0) * 10 - COALESCE(nscs.total, 0) * 10 + COALESCE(c.total, 0) AS totalScore2 
    FROM login l  
    LEFT JOIN (
     SELECT loginid, COUNT(1) AS total 
     FROM submission 
     GROUP BY loginid 
    ) s ON l.loginid = s.loginid 
    LEFT JOIN (
     SELECT loginid, COUNT(1) AS total 
     FROM comment 
     GROUP BY loginid 
    ) c ON l.loginid = c.loginid 

    LEFT JOIN (
     SELECT S2.loginid, COUNT(1) AS total 
     FROM submission S2 
     INNER JOIN comment C2 
     ON C2.submissionid = S2.submissionid 
     GROUP BY S2.loginid 
    ) scs ON scs.loginid = l.loginid 


    LEFT JOIN (
     SELECT S2.loginid, COUNT(1) AS total 
     FROM submission S2 
     INNER JOIN comment C2 
     ON C2.submissionid = S2.submissionid 
    AND C2.loginid = S2.loginid 
     GROUP BY S2.loginid 
    ) nscs ON nscs.loginid = l.loginid 



    GROUP BY l.loginid 
    ORDER BY totalScore2 DESC 
    LIMIT 25";