Answer the question
In order to leave comments, you need to log in
How to select only one row with desired values?
Hello everyone,
There is a table with users, where each user has an id,
and there is a table with messages, where each message is a string and has two fields for senders id. There are a lot of messages, some match on both id.
Example:
Where "id" is the sequence number of the message, "fsender_id" is the sender's id, and "ssender_id" is the recipient's id.
Suppose a request is made for a user with id = 1. Then all messages sent to him or him will have fsender_id = 1 or ssender_id = 1. Then you need to select from the table only those rows where fsender_id or ssender_id is equal to 1, and where the id of the second user (fsender_id or ssender_id) is not repeated. That is, according to the presented table, the result should be only rows with id 1 and 6.
Answer the question
In order to leave comments, you need to log in
Select through where messages where the user is the sender or recipient.
Then group "by counterparty" and select a larger departure number from the group (if you still need the last, not the first messages).
CREATE TABLE m (
id INTEGER(11) NOT NULL AUTO_INCREMENT,
u_from INTEGER(11) NOT NULL,
u_to INTEGER(11) NOT NULL,
PRIMARY KEY USING BTREE (id)
) ENGINE=InnoDB
AUTO_INCREMENT=8 CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'
;
INSERT INTO `m` (id, u_from, u_to) VALUES
(1,7,1),
(2,7,1),
(3,7,1),
(4,7,1),
(5,1,7),
(6,1,4),
(7,4,1);
COMMIT;
select
max(id) id,
if(u_from = 1, concat('TO ', u_to), concat('FROM ', u_from)) last_msg,
u_from,
u_to
from m
where u_from = 1 or u_to = 1
group by if(u_from = 1, u_to, u_from)
order by id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question