[英]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.