tags:

views:

49

answers:

2

I'm making a tool to track calls to house/senate reps, and I have 2 tables of importance here:

reps

rep_id
rep_name # and more info

comments

rep_id
status # enum about result of contact
comment

I want to query for all reps joining the most recent associated comments and in some cases joining comments of a specific status, but there might not be any comments associated with that rep yet.

THANKS!

+1  A: 

EDIT:

Use a left join to get all reps,

SELECT reps.rep_id, comments.comment
FROM reps
LEFT JOIN comments
ON reps.rep_id=comments.rep_id
ViralShah
OP wants all reps, not just those with comments
KM
Sorry, misread the question. KM, your solution looks spot on in that case.
ViralShah
@ViralShah, yea I had to read it a bunch of times myself... your latest edit now shows all reps with all of their comments, not just a single row per rep with the latest comment.
KM
+3  A: 

you need some way to distinguish latest comment, so I made up a new column: comments.commentDate, with that or some auto number/identity use a query like this:

SELECT
    r.*,c.*
    FROM reps r
        LEFT OUTER JOIN (SELECT
                             rep_id,MAX(commentDate) AS MaxDate
                             FROM comments
                             GROUP BY rep_id
                        ) m On r.rep_id=m.rep_id
        LEFT OUTER JOIN comments c ON r.rep_id=c.rep_id AND m.MaxDate=c.commentDate
    ORDER BY r.rep_name
KM
KM, can you add m.comments to the first SELECT, add comments to the subquery and derived table, and skip the third join?
Marcus Adams
@Marcus Adams, No. The "M" derived table finds the last comment row per rep. Once you find that max row, you have to join back to the same table to get the remaining columns. When working with GROUP BY the only columns that can appear in the select list are the columns to group by and aggregate functions (functions that combine rows). By grouping by rep_id, you get one row per rep_id. If you try to group by the rep_id and comment, you get one row for each rep_id and comment (which will be many per a single rep_id).
KM
@KM, Oh yeah, you're right. I don't know what I was thinking.
Marcus Adams
Excellent, thanks! Usually I wouldn't ask someone else to do my SQL work, but this is unpaid work for the benefit of the public sector. You can see what I'm doing here at http://pledge.santiance.com
Kristopher Ives