MySQL查询与他人的用户对话

时间:2019-07-02 05:38:37

标签: mysql sql

我想查询特定用户与他人的对话。

该表记录了每个消息信息,例如发送者和接收者的用户ID:

CREATE TABLE now_user_chat (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) unsigned NOT NULL COMMENT 'user id',
  `to_uid` int(20) unsigned NOT NULL COMMENT 'send to user id',
  `speak_time` int(11) unsigned NOT NULL COMMENT 'speak time',
  `content` varchar(600) DEFAULT NULL COMMENT '',
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`),
  KEY `to_uid` (`to_uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

!记录不正常:

| id | uid | to_uid | speak_time |  content |
|----|-----|--------|------------|----------|
|  1 |   1 |      2 |          10 | [0102] A |
|  2 |   2 |      1 |          20 | [0102] B |
|  3 |   2 |      1 |          30 | [0102] D |
|  4 |   1 |      3 |          40 | [0103] A |
|  5 |   2 |      3 |          50 | [0203] A |
|  6 |   3 |      1 |          60 | [0103] B |
|  7 |   4 |      3 |          70 | [0304] A |
|  8 |   3 |      4 |          80 | [0304] B |
|  9 |   2 |      4 |          90 | [0204] A |
| 10 |   1 |      3 |         100 | [0103] C |
| 11 |   1 |      2 |         110 | [0102] D |
| 12 |   2 |      1 |          120 | [0102] C |
| 13 |   2 |      1 |          25 | [0102] C |

sqlfiddle

我想按目标组查询用户ID 1与其他人的对话,并且少于speak_time的{​​{1}}并按110的升序查询。结果看起来像这样:

目标组中的记录按speak_time升序排列,可以在时间轴中显示。

speak_time

如何编写SQL查询?

--------编辑----------

| id | target_group | uid | to_uid | speak_time | content | |----|--------------|--------|--------|------------|----------| | 1 | 2 | 1 | 2 | 10 | [0102] A | | 2 | 2 | 2 | 1 | 20 | [0102] B | | 13 | 2 | 2 | 1 | 25 | [0102] C | | 3 | 2 | 2 | 1 | 30 | [0102] D | | 4 | 3 | 1 | 3 | 40 | [0103] A | | 6 | 3 | 3 | 1 | 60 | [0103] B | | 10 | 3 | 1 | 3 | 100 | [0103] C | 就是与用户ID target_group交谈的人,并且只有一张桌子。

2 个答案:

答案 0 :(得分:0)

嗨,我想这就是你想要的。

select * from now_user_chat where (uid = 1 or to_uid =1 ) and speak_time < 11

SQL小提琴演示link enter image description here

答案 1 :(得分:0)

尝试一下-

select
    x.id,
    (case when x.uid = 1 then x.to_uid else x.uid end) as target_group,
    x.uid,
    x.to_uid,
    x.speak_time,
    x.content 
from now_user_chat x
where (x.uid = 1 or x.to_uid = 1)
    and x.speak_time < 11
order by x.speak_time asc;