Background
I have a table of comments. Each comment belongs to a specific row in the ‘lead’ table or the ‘prod’ table. There can be multiple comments for each row in the ‘lead’ and ‘prod’ tables. There can also be multiple comments with the same ‘kstatus’ for each row.
comments
INT id /* primary key */
ENUM('lead', 'prod') type /* tells me whether the comment belongs to a row in the lead table or the prod table */
INT fid /* foreign key, refers to the id column in either the lead or prod table */
MEDIUMTEXT comment /* the comment itself */
INT timestamp /* when the comment was written, i.e. 1300530201 */
INT kstatus /* foreign key, refers to the id column in the kstatus column */
lead
INT id
...
prod
INT id
...
kstatus
INT id
...
A comment with type = ‘lead’ and fid = 105 refers to the row in lead with lead.id = 105.
A comment with type = ‘prod’ and fid = 105 refers to the row in prod with prod.id = 105.
Question
I want to SELECT the first comment given (if any, and based on timestamp) for each row in the ‘lead’ table with a certain kstatus (say 14).
Here is my attempt, which returns way too few results. Maybe due to mixing of fid’s referring to lead.id and fid’s referring to prod.id?
SELECT C1.*
FROM comments AS C1
LEFT JOIN comments AS C2 ON (C1.timestamp > C2.timestamp AND C1.fid = C2.fid)
WHERE C2.timestamp is NULL
AND C1.type = 'lead'
AND C1.kstatus = 14
GROUP BY C1.fid
1 Answer