简体   繁体   English

用户通过组对话mysql选择消息

[英]group conversation by users mysql select for messages

Table: 表:

CREATE TABLE `messages` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `from_user_id` int(11) unsigned NOT NULL,
  `to_user_id` int(11) unsigned NOT NULL,
  `seen` tinyint(1) NOT NULL DEFAULT '0',
  `sent` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `message` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO `messages` (`id`, `from_user_id`, `to_user_id`, `seen`, `sent`, `message`)
VALUES
    (1,2,1,0,'2013-11-06 11:05:42','Hello!'),
    (2,1,2,0,'2013-11-06 11:05:52','Hello you too!'),
    (3,3,1,0,'2013-11-06 11:06:08','Whats up?'),
    (4,1,3,0,'2013-11-06 11:06:27','Not much');

I would put this in sqlfiddle but it is down for me, I cannot access it last 32 hours. 我会将其放在sqlfiddle中,但对我而言它是无效的,我无法在最近32小时内访问它。

I've searched SO and found several related topics, but with different grouping requirements so I could not apply them to my project. 我搜索了SO,发现了几个相关的主题,但是具有不同的分组要求,因此无法将其应用于我的项目。

For the query, I know current user id and target user id, and based on this I want query to return all conversation of these two users ordered by date. 对于查询,我知道当前用户ID和目标用户ID,并基于此查询,我希望查询返回按日期排序的这两个用户的所有对话。

I was thinking something like: 我在想类似的东西:

SELECT message FROM messages WHERE from_user_id = 1 OR to_user_id = 1 [but where do I limit this query to target user 3?]

In other words I want to select: 换句话说,我要选择:

(3,3,1,0,'2013-11-06 11:06:08','Whats up?')
(4,1,3,0,'2013-11-06 11:06:27','Not much')

For user 1, conversation with user 3. All of it. 对于用户1,与用户3的对话。

SELECT message FROM messages 
WHERE 1 in (from_user_id,to_user_id) and 3 in (from_user_id,to_user_id)

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

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