我有一张评论表。每条评论都属于'lead'表或'prod'表中的特定行。 “lead”和“prod”表中的每一行都可以有多个注释。每行也可以有多个相同的'kstatus'注释。
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
...
type ='lead'和fid = 105的注释引用lead的行,其中lead.id = 105。 type ='prod'和fid = 105的注释引用prod.id = 105的prod行。
我想选择带有特定kstatus(比如14)的'lead'表中每一行给出的第一条评论(如果有的话,并根据时间戳)。
这是我的尝试,返回的结果太少了。也许是由于fid的混合引用了lead.id和fid指的是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
答案 0 :(得分:0)
select c2.*
from (
select min(c.id) realfirstcomment
from (
select fid, min(timestamp) as firstcomment
from comments
where type='lead' and kstatus=14
group by fid
) f, comments c
where f.fid = c.fid
and c.type='lead' and c.kstatus=14
and f.firstcomment = c.timestamp
group by c.fid
) f2, c2
where f2.realfirstcomment = c2.id
答案 1 :(得分:0)
由于产品和潜在客户之间的混合,您不仅会失去结果,而且在kstatus值之间也是如此 - 您的左连接会在C2
中查找具有较早时间戳的所有行,无论类型和kstatus如何因为fid
是相同的。
一种解决方案是将AND C1.type = C2.type AND C1.kstatus = C2.kstatus
添加到连接条件。