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:
The
loginid
whenl.username = '$profile'
is found.All the
submissionid
s are found that have theloginid
from #1 above.All the
commentid
s with thesubmissionid
s from #2 above are found, and the correspondingpoints
are summed.
Now, how could I make a different query that returns an array of all of the comment
s in #3 above rather than summing the point
s?
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).
精彩评论