查询双方之间的消息,但隐藏消息给删除的用户

时间:2014-07-06 21:00:39

标签: 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 and u_id=02),我想再次在sender_deleted=yes时向sender_id隐藏消息,但向recipient_id显示相同的消息如果recipient_deleted = no

NB-UPDATE

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

  2. 我希望u_id=02的用户在其页面上查看时看到m_id=100m_id=200的邮件

  3. 这就是我所尝试过的,但我已经知道如何去做了

    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)
    

2 个答案:

答案 0 :(得分:1)

这是一个解决方案。它的工作原理是过滤用户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(01或02)替换<id>

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

希望这有帮助!

答案 1 :(得分:1)

以下查询返回问题中发布的所需消息列:

SELECT
msg_details.sender_id,
msg_details.Body,
u.Name,
u.u_id
FROM users u
INNER JOIN messages msg_details ON u.u_id = msg_details.sender_id
LEFT JOIN messages m ON msg_details.m_id = m.m_id
LEFT JOIN recipient r ON msg_details.m_id = r.m_id
WHERE (m.sender_id = <user_id> AND m.sender_deleted = 'no')
OR (r.recipient_id = <user_id> AND r.recipient_deleted = 'no');

user_id替换为当前的user_id

SQL Fiddle demo

相关问题