简体   繁体   English

mysql查询以获取属于用户联系人的所有消息

[英]mysql query for getting all messages that belong to user's contacts

So I have a database that is setup sort of like this (simplified, and in terms of the tables, all are InnoDBs): 因此,我有一个这样的数据库(简化了,就表而言,它们都是InnoDB):

Users:    contains based user authentication information (uid, username, encrypted password, et cetera)
Contacts: contains two rows per relationship that exists between users as
          (uid1, uid2), (uid2, uid1) to allow for a good 1:1 relationship
          (must be mutual) between users
Messages: has messages that consist of a blob, owner-id, message-id (auto_increment)

So my question is, what's the best MySQL query to get all messages that belong to all the contacts of a specific user? 所以我的问题是,要获取属于特定用户所有联系人的所有消息的最佳MySQL查询是什么? Is there an efficient way to do this? 有一种有效的方法可以做到这一点吗?

select m.owner-id, m.blob 
  from Users u
  join Contacts c on u.uid = c.uid1
  join Messages m on m.owner-id = c.uid2
 where u.username = 'the_username';

Now the thing is here that this will return every message owned by all of the contacts regardless of whether the message was associated with some interaction between uid1 and uid2. 现在的问题是,这将返回所有联系人拥有的每条消息,而不管该消息是否与uid1和uid2之间的某些交互关联。

Also if you want to see the contact names next to the messages instead of a uid: 另外,如果您想查看消息旁边的联系人姓名而不是uid:

select u2.username, m.blob 
  from Users u
  join Contacts c on u.uid = c.uid1
  join Messages m on m.owner-id = c.uid2
  join Users u2 on u2.uid = c.uid2
 where u.username = 'the_username';

hmm after re-reading your question - I noticed that "must be mutual thing". 重新阅读您的问题后,嗯-我注意到“必须是共同的东西”。 That sounds like you would also need an exists query to check on that part to restrict the results to only mutual relationships. 听起来您还需要一个存在查询来检查该部分,以将结果限制为仅相互关系。

Might be easier to write if you provided sample table definitions. 如果提供了示例表定义,则编写起来可能会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM