繁体   English   中英

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

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

因此,我有一个这样的数据库(简化了,就表而言,它们都是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)

所以我的问题是,要获取属于特定用户所有联系人的所有消息的最佳MySQL查询是什么? 有一种有效的方法可以做到这一点吗?

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';

现在的问题是,这将返回所有联系人拥有的每条消息,而不管该消息是否与uid1和uid2之间的某些交互关联。

另外,如果您想查看消息旁边的联系人姓名而不是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';

重新阅读您的问题后,嗯-我注意到“必须是共同的东西”。 听起来您还需要一个存在查询来检查该部分,以将结果限制为仅相互关系。

如果提供了示例表定义,则编写起来可能会更容易。

暂无
暂无

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

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