[英]selecting rows from table which have distinct values for a column
In my thread based messaging system, the table schema is 在基于线程的消息传递系统中,表架构为
> 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
Here, I want to select the first message id which is sent to a new receiver and sender is the user who is logged in. 在这里,我要选择发送到新的接收者的第一个消息ID,发送者是已登录的用户。
Doing this with multiple queries and some code is obviously possible but can it be done with a single query for performance issues?? 用多个查询和一些代码执行此操作显然是可能的,但是可以通过单个查询来解决性能问题吗?
You can try 你可以试试
EDIT: 编辑:
If the id is auto increment, then the id will also increase with time and you can use: 如果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>
Here's my best guess as to what you want, but it would be easier if you gave known inputs, example data, and expected output. 这是您想要的最好的猜测,但是如果您提供已知的输入,示例数据和预期的输出,则将更加容易。
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
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
join message reference with "maxtime per reciever" table on reciever and time 在“接收者和时间”表上使用“每个接收者的最大时间”表加入消息引用
Well I got the answer, Just a group by query worked the way I wanted. 好吧,我得到了答案,只是按查询分组按我想要的方式工作。 I used query
我用查询
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`
Thanks everyone for the help. 谢谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.