I'm using derived tables (latest version of MySQL) to get counts and data from other tables, in to my main result set. One of the small queries in a LEFT OUTER JOIN is causing me a problem. I'm trying to get the date of the latest comment made by this blog member, using a LIMIT 1 condition. The entire query below grabs the member's account details and activity/login statistics.
SELECT mem.member_id, mem.screen_name, mem.firstname, mem.lastname,
mem.email, mem.add1, mem.add2, mem.town, mem.county,
mem.post_code, mem.country_code, mem.country_name, mem.joined, mem.member_status,
IFNULL(rep.rep,0) as reputation,
IFNULL(com.cnt,0) as comments,
com1.lcomm as last_comment
FROM members AS mem
LEFT OUTER JOIN (
SELECT member_id, SUM(awarded_what) as rep
FROM members_reputation
GROUP BY member_id) rep
ON mem.member_id = rep.member_id
LEFT OUTER JOIN (
SELECT member_id, COUNT(comment_id) as cnt
FROM blog_comments
GROUP BY member_id) com
ON mem.member_id = com.member_id
LEFT OUTER JOIN (
SELECT member_id, posted as lcomm
FROM blog_comments
ORDER BY posted DESC LIMIT 1) com1 **** problem with LIMIT
ON mem.member_id = com1.member_id
// more left outer join sub queries to other tables
WHERE mem.member_id = 1
GROUP BY mem.member_id
Where I have marked the query as a problem, is where the problem lies. If I use ORDER BY posted DESC LIMIT 1
, even though there are 4 comments by this member, it sometimes doesn't return a last_comment date but some times does - not sure of the pattern. If I remove the LIMIT 1 it works fine, but I'm worried it's returning all the comment dates, rather than just the latest date on its own, causing me issues when the DB grows.
What is going on here? Why is LIMIT 1 sometimes not returning a last_comment date? Is my query, without the LIMIT condition, returning all comment dates? An explanation/suggestion would be fantastic.
here's your problem
LEFT OUTER JOIN (
SELECT member_id, posted as lcomm
FROM blog_comments
ORDER BY posted DESC LIMIT 1) com1 **** problem with LIMIT
ON mem.member_id = com1.member_id
in your other left join stanza's you're doing a group by... but in the above problem one, you are relying on the join clause to restrict your set to member_id, however you've already ordered and limited by then...
which means sometimes the (one) result does not match your join criteria resulting in an empty lcomm
you need a where clause like this
LEFT OUTER JOIN (
SELECT member_id, posted as lcomm
FROM blog_comments
WHERE member_id = X
ORDER BY posted DESC LIMIT 1) com1
ON mem.member_id = com1.member_id
(" _
in your joins are syntax errors. CopyPasta glitch - Marc B 2012-04-04 21:54