我找到了类似的科目,但却得不到我想要的东西。
我有3张桌子:
MESSAGE(行:MID,CONTENT,SENTDATE)
RECEIVED(行:RID,MEMBRE,FK_RE_MESSAGE_ID(外键:message.ID))
GROUP(行:GID,MICROID,FK_GR_MESSAGE_ID(外键:message.ID))
我想获取每个组的最后一条消息,以获取会员ID 基于谷歌搜索,这是我尝试过的最后一个请求:
SELECT *
FROM MESSAGE as msg
LEFT JOIN RECEIVED AS rcd ON msg.MID=rcd.FK_RE_MESSAGE_ID
LEFT JOIN GROUP AS grp ON msg.MID=grp.FK_GR_MESSAGE_ID
INNER JOIN (SELECT MID, MAX( SENTDATE) AS lastdate
FROM MESSAGE
GROUP BY MID) MESSAGE ON msg.MID=MESSAGE.MID
WHERE (rcd .MEMBRE)*
这将返回所选组的任何组中的所有消息。
请有人帮帮我吗?
答案 0 :(得分:1)
您只需修复上一个join
条件:
SELECT *
FROM MESSAGE as msg LEFT JOIN
RECEIVED AS rcd
ON msg.MID=rcd.FK_RE_MESSAGE_ID LEFT JOIN
"GROUP" AS grp
ON msg.MID=grp.FK_GR_MESSAGE_ID INNER JOIN
(SELECT MID, MAX( SENTDATE) AS lastdate
FROM MESSAGE
GROUP BY MID
) MESSAGE
ON msg.MID = MESSAGE.MID and msg.SENTDATE = MESSAGE.lastdate
WHERE (rcd .MEMBRE)*;
如果您要过滤数据并在MESSAGE(MID, SENTDATE)
上设置索引,则以下内容应该会更好;
SELECT *
FROM MESSAGE as msg LEFT JOIN
RECEIVED AS rcd
ON msg.MID = rcd.FK_RE_MESSAGE_ID LEFT JOIN
"GROUP" AS grp
ON msg.MID = grp.FK_GR_MESSAGE_ID
WHERE (rcd .MEMBRE)* and
not exists (select 1
from message m2
where m2.mid = msg.mid and m2.sentdate > msg.sentdate
);