简体   繁体   English

如何从表格中检索不同的行

[英]How do i retrieve distinct rows from a table

I have a table in my database called message where users can send and retrieve messages. 我的数据库中有一个名为message的表,用户可以在其中发送和检索消息。

Here is the layout: 这是布局:

msg_id sender_id receiver_id date txt msg_id sender_id receiver_id 日期 txt

I want to be able to retrieve messages sent to a particular user, with only the last message for each user eg There might be more than one Message from user id 1 , but I only want to display the last message. 我希望能够检索发送给特定用户的消息,每个用户只有最后一条消息,例如,用户ID 1可能有多个消息,但是我只想显示最后一条消息。

http://sqlfiddle.com/#!9/81b57/3 http://sqlfiddle.com/#!9/81b57/3

SELECT m.*
FROM messages m
LEFT JOIN messages m1
ON m.sender_id = m1.sender_id
  AND m.date<m1.date
WHERE m1.msg_id IS NULL
ORDER BY sender_id

OR 要么

SELECT m.*
FROM messages m
LEFT JOIN messages m1
ON m.receiver_id = m1.receiver_id
  AND m.date<m1.date
WHERE m1.msg_id IS NULL
ORDER BY receiver_id;

UPDATE Here is variant with flexible limit (2-3-4 ...any) of records per user. 更新这是每个用户记录的灵活限制(2-3-4 ... any)的变体。 But keep in mind it could become very slow if you have millions of records. 但是请记住,如果您有数百万条记录,它可能会变得非常缓慢。

http://sqlfiddle.com/#!9/81b57/13 http://sqlfiddle.com/#!9/81b57/13

SELECT m.*
FROM
(SELECT *, 
   IF(@user=receiver_id,@user_index:=@user_index+1,@user_index:=1) idx,
   @user:=receiver_id
FROM messages 
ORDER BY receiver_id, `date` DESC
) m
WHERE m.idx<=2

**UPDATE 2* One another approach. **更新2 *另一种方法。 I guess it could be faster: 我想可能会更快:

http://sqlfiddle.com/#!9/6bfbd/1 http://sqlfiddle.com/#!9/6bfbd/1

SELECT m.*
FROM messages m
INNER JOIN (
  SELECT receiver_id, 
  GROUP_CONCAT(msg_id ORDER BY `date` DESC) ord
  FROM messages 
  GROUP BY receiver_id

) o
ON o.receiver_id = m.receiver_id
  and FIND_IN_SET(m.msg_id, o.ord) BETWEEN 1 AND 2
ORDER BY m.receiver_id, m.date DESC
  ;

You need use ORDER BY and LIMIT for your query 您需要对查询使用ORDER BYLIMIT

Example: 例:

SELECT * FROM message WHERE receiver_id=1 ORDER BY date DESC LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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