简体   繁体   中英

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM