mysql - 查询两方之间的消息,但对删除的用户隐藏消息

标签 mysql sql

我正在构建一个消息传递系统,下面是我的表格。

table --users
          |u_id | Name |
          | 01  | Aku  |
          | 02  | Sika |
          | 03  | Admin|

table --messages 
          |m_id | sender_id | Body   | sender_deleted | msgTime |
          | 100 |  01       | hello  |     Yes        | 16:04   |
          | 200 |  02       | Hi     |     no         | 16:08   |


table --recipient
          |m_id | recipient_id | status | recipient_deleted |
          |100  |   02         | read   |  no               |
          |200  |   01         | unread |  no               |

问题

我想从这些表中查询仅在两方之间的对话(因此u_id=01和u_id=02),我再次想在sender_deleted=yes<时隐藏发送给sender_id的消息 但如果 recipient_deleted = no

则向 recipient_id 显示相同的消息

NB-更新

  1. 我希望 u_id=01 的用户在其页面上查看时只能看到带有 m_id=200 的消息

  2. 我希望 u_id=02 的用户在其页面上查看时能够看到包含 m_id=100m_id=200 的消息

这是我尝试过的,但我不知道如何去做

SELECT
      m.sender_id,
      m.Body,
      u.Name,
      u.u_id
FROM 
      messages m
LEFT JOIN
      users u
   ON 
      m.sender_id=u.u_id
LEFT JOIN
      recipient r
   ON
      r.m_id=m.m_id
WHERE
      (m.sender_id=01 OR m.sender_id=02 ) and 
      (r.recipient_id=01 OR r.recipient_id=02)

最佳答案

这是一种解决方案。它的工作原理是过滤用户 01 和 02 之间交换的消息,并仅显示与登录用户相关的消息:

SELECT m.sender_id, m.recipient_id, m.Body, u_sender.Name as Sender,
       u_recipient.Name as Recipient, sender_deleted, recipient_deleted
FROM messages m
JOIN recipient r ON (m.m_id=r.m_id)
JOIN user u_sender ON (m.sender_id=u_sender.u_id)
JOIN user u_recipient ON (r.recipient_id=u_recipient.u_id)
WHERE 
     m.sender_id IN (01,02) 
 AND 
     r.recipient_id ON (01,02)
 AND
     ((m.sender_id=<id> AND m.sender_deleted='no') 
       OR 
     (r.recipient_id=<id> AND r.recipient_deleted='no'))

您应该替换<id>登录的用户 ID(01 或 02)

当然,您可以更改返回的字段以显示您需要的内容。

希望这有帮助!

关于mysql - 查询两方之间的消息,但对删除的用户隐藏消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24600293/

相关文章:

mysql - 混合变量赋值和数据检索——MySQL 与 MS SQL Server

php - postgresql - 当用户名用base64编码时如何进行查询搜索?

mysql - Symfony2 在 Symfony 和 csv 文件中添加查询日志记录

使用前缀和干扰词的 SQL Server 全文搜索

mysql - 与 SQL 聚合不同的计数

mysql - 如何使用 mysql 根据同一个表的其他两列填充列?

mysql 存储功能不起作用

mysql - 如何将多个转储命令结果合并到同一数据库的mysql中的单个文件中

php - 在 While 循环中对结果进行分组并计数值

php - 我无法使用 PDO 计算数据库中的结果