dongpo2014 2011-05-20 18:40
浏览 31
已采纳

来自3个表的MySQL数据

I have three MySQL tables which relate to a messaging system. The schema and sample data is shown below for each table relating to my question:

`messages`:
+----+---------+----------+
| id | subject | senddate |
+----+---------+----------+
| 1  | Testing | 12344555 |
+----+---------+----------+

`message_senders`:
+------------+---------+---------+
| message_id | user_id | trashed |
+------------+---------+---------+
|      1     |    1    |    1    |
+------------+---------+---------+

`message_recipients`:
+------------+---------+------+----------+---------+
| message_id | user_id | type | readdate | trashed |
+------------+---------+------+----------+---------+
|      1     |    1    |  to  | 12344555 |    1    |
+------------+---------+------+----------+---------+
|      2     |    1    |  cc  | 12344555 |    1    |

My question is how would I select all messages sent by or received by a user, where the trashed parameter is set to 1, without selecting duplicate messages. For example, consider the following scenario:

I want to get the message IDs for all messages trashed by user_id 1, but I don't want to retrieve duplicate IDs (in the data above for example, user_id 1 is the sender AND recipient of message_id 1. I don't want to return the message_id of 1 twice, but want to get all messages for that user.

I think I need to use a combination of JOIN and UNION, but my brain isn't functioning after a long day of PHP!

  • 写回答

4条回答 默认 最新

  • dqypcghd381390 2011-05-20 18:46
    关注

    Try this and see if it only returns one row for each message in the messages table...

        select * from messages 
    left join message_senders on messages.id = message_senders.message_id 
    left join message_recipients on messages.id = message_recipients.message_id 
    where message_senders.trashed = 1 or message_recipients.trashed = 1 and messages.user_id = <value>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?