开发者

Modifying a query that had a left join and an inner join

The query below sums up points from the MySQL table "comment" when the following conditions are met:

  1. The loginid when l.username = '$profile' is found.

  2. All the submissionids are found that have the loginid from #1 above.

  3. All the commentids with the submissionids from #2 above are found, and the corresponding points are summed.

Now, how could I make a different query that returns an array of all of the comments in #3 above rather than summing the points?

Here are the MySQL tables involved:

login:

logind username created activated

submission:

submissionid loginid

comment:

commentid submissionid points comment

Query:

SELECT 
    l.loginid, 
    l.username, 
    l.created,
    l.activated,
    COALESCE(scs.total, 0) AS commentsreceivedvalue

FROM login l    


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


WHERE l.act开发者_如何学Civated = 1
AND l.username = '$profile'


GROUP BY l.loginid
ORDER BY commentsreceivedvalue DESC 


Isn't it as simple as:

SELECT l.loginid, l.username, l.created, l.activated, scs.commentid, scs.comment
  FROM login AS l
  LEFT JOIN (SELECT S2.loginid, c2.commentid, c2.comment 
               FROM submission AS S2
               JOIN comment    AS C2 ON S2.submissionid = C2.submissionid
            ) AS scs ON scs.loginid = l.loginid
 WHERE l.activated = 1
   AND l.username = '$profile'
 ORDER BY scs.commentid DESC;

The outer GROUP BY in the original was not doing anything useful. The ORDER BY in the original was replaced here by the ordering in reverse order of comment ID, which is an approximation to reverse chronological order (most recent first, in other words).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜