修改连接查询以向查询添加新值

时间:2010-10-08 08:24:13

标签: php mysql

以下查询效果很好。它从3个MySQL表中提取信息:登录,提交和评论。

根据从这三个表中提取的值的计算,它会创建一个名为totalScore2的值。

MySQL表“评论”和“提交”都有以下字段:

loginid submissionid

在表“提交”中,每个“submitid”只有一个条目/行,因此只有一个“loginid”与之关联。

在表“comment”中,字段“submissionid”可以有多个条目/行,并且可以与多个“loginid”相关联。

每次“评论”中的“提交者”之一与“提交”表中的“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";

1 个答案:

答案 0 :(得分: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";