表:
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');
我会把它放在sqlfiddle中,但对我而言,我无法在32小时内访问它。
我搜索了SO并找到了几个相关的主题,但是有不同的分组要求,所以我无法将它们应用到我的项目中。
对于查询,我知道当前用户ID和目标用户ID,并根据此我想查询返回按日期排序的这两个用户的所有会话。
我在想这样的事情:
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?]
换句话说,我想选择:
(3,3,1,0,'2013-11-06 11:06:08','Whats up?')
(4,1,3,0,'2013-11-06 11:06:27','Not much')
对于用户1,与用户3的对话。所有这些。
答案 0 :(得分:4)
SELECT message FROM messages
WHERE 1 in (from_user_id,to_user_id) and 3 in (from_user_id,to_user_id)