在我的基于线程的消息传递系统中,表模式是
> messages table
id(int auto incr primary key)
body(varchar)
time(datetime)
>message_reference table
id(int auto incr primary key)
message_id(forgain key from message table)
sender
receiver
在这里,我想选择发送给新接收者的第一个消息ID,发件人是登录的用户。
使用多个查询和一些代码执行此操作显然是可行的,但可以通过单个查询来解决性能问题吗?
答案 0 :(得分:1)
你可以尝试
编辑:
如果id是自动递增,那么id也会随着时间的推移而增加,您可以使用:
SELECT message_reference.message_id, message_reference.receiver, messages.body
FROM message_reference, messages
WHERE message_reference.message_id IN (SELECT MIN(message_reference.message_id)
FROM message_reference
GROUP BY message_reference.receiver)
AND message_reference.message_id = messages.id AND message_reference.sender = <sender>
答案 1 :(得分:0)
这是我对你想要的最好的猜测,但是如果你给出已知输入,示例数据和预期输出会更容易。
SELECT
MR2.message_id
FROM (
SELECT
MR.sender,
MR.receiver,
M.MIN(`time`) AS min_time
FROM
Message_References MR -- Either use plural names (my personal preference) or singular, but don't mix them
INNER JOIN Messages M ON
M.id = MR.message_id
WHERE
MR.sender = <sender>
GROUP BY
MR.received) SQ
INNER JOIN Message_References MR2 ON
MR2.sender = SQ.sender AND
MR2.receiver = SQ.receiver AND
MR2.`time` = SQ.min_time
答案 2 :(得分:0)
select mr.message_id from
message_reference as mr inner join
(select mr1.reciever max(m1.time) as time from messages as m1
inner join message_reference as mr1 on mr1.message_id = m1.id
group by mr1.reciever) as last
on mr.reciever = last.reciever and mr.time = last.time
在接收者和时间上加入带有“每个接收者的最大时间”表的消息参考
答案 3 :(得分:0)
嗯,我得到了答案,只是一组查询以我想要的方式工作。我用了查询
SELECT SENDER,
RECEIVER,
BODY,
TIME,
MESSAGE_ID
FROM MESSAGE_REF JOIN MESSAGE
ON MESSAGE.ID=MESSAGE_REF.MESSAGE_ID
ORDER BY 'TIME' GROUP BY RECEIVER`
感谢大家的帮助。