![](/img/trans.png)
[英]How to select row from two different tables using specific id in mysql?
[英]How to select messages from two different tables in a specific order with Mysql?
總共有五個數據表:
theUser (*id*, name)
theGroup (*id*, name)
Membership (*group_id*, *user_id*)
gpMsge (*id*, sender, receiver, content, time) # message within group
idMsge (*id*, sender, receiver, content, time) # message between user and user
從這個問題解釋了theUser
, theGroup
和Membership
之間的關系。 現在我要提取的會話( gpMsge
和idMsge
),並顯示相應的發送者的名稱( theUser
和theGroup
在那個談話newset消息的順序)。 實際上, Whatsapp
的業務邏輯是完全相同的。 在第一部分中,發件人名稱(如果會話為p2p,則為個人用戶名;如果位於組內,則為組名),並按該會話中最新消息的時間順序顯示。 在每個發件人姓名下,該會話中應該有五個最新消息。 在第二部分中,顯示沒有對話的所有組(無需在此部分中指定順序)。
對於我來說,現在的困難是對話的順序,因為gpMsge
和idMsge
是孤立的。 我如何排序的time
在每個表中的值,並獲得名字theUser
和theGroup
在表中? 先感謝您!
您可以使用“ UNION”,以便可以比較兩個不同表之間的時間
該查詢將列出兩個表中的最后5個會話。
SELECT id,sender,receiver,content,time
FROM gpMsge
UNION
SELECT id,sender,receiver,content,time
FROM idMsge
ORDER BY time DESC
LIMIT 5
完整的查詢將是這樣的:
SELECT US.name AS sender,GR.name AS receiver,content,time
FROM gpMsge AS GM
LEFT JOIN theUser AS US ON GM.sender=US.id
LEFT JOIN theGroup AS GR ON GM.receiver=GR.id
UNION
SELECT US.name AS sender,UR.name AS receiver,content,time
FROM idMsge AS UM
LEFT JOIN theUser AS US ON UM.sender=US.id
LEFT JOIN theUser AS UR ON UM.receiver=UR.id
ORDER BY time DESC
LIMIT 5;
如果要選擇一個特定的發送者或接收者,則必須在WHERE子句中添加它:
此查詢將選擇發送給接收者的所有ID為2的會話:將直接消息發送給該用戶,或發送給具有該用戶作為成員的組的消息。
對於您的最后一個問題,您可以添加一個額外的字段來檢查消息是從組內還是組外的用戶發送的,可以是一些文本或int ...
SELECT US.name AS sender,GR.name AS receiver,content,
"This is a message in a group" AS sent_from,time
FROM gpMsge AS GM
LEFT JOIN theUser AS US ON GM.sender=US.id
LEFT JOIN theGroup AS GR ON GM.receiver=GR.id
WHERE receiver IN (
SELECT group_id FROM Membership WHERE user_id=2
)
UNION
SELECT US.name AS sender,UR.name AS receiver,content,
"This is a message from a user" AS sent_from, time
FROM idMsge AS UM
LEFT JOIN theUser AS US ON UM.sender=US.id
LEFT JOIN theUser AS UR ON UM.receiver=UR.id
WHERE receiver=2
ORDER BY time DESC
LIMIT 5;
獲取所有具有特定用戶作為成員且尚未收到消息的組:
SELECT id,name
FROM Membership AS M
JOIN theGroup AS G ON M.group_id=G.id
WHERE user_id=2
AND group_id NOT IN (SELECT receiver FROM gpMsge);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.