簡體   English   中英

如何使用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

從這個問題解釋了theUsertheGroupMembership之間的關系。 現在我要提取的會話( gpMsgeidMsge ),並顯示相應的發送者的名稱( theUsertheGroup在那個談話newset消息的順序)。 實際上, Whatsapp的業務邏輯是完全相同的。 在第一部分中,發件人名稱(如果會話為p2p,則為個人用戶名;如果位於組內,則為組名),並按該會話中最新消息的時間順序顯示。 在每個發件人姓名下,該會話中應該有五個最新消息。 在第二部分中,顯示沒有對話的所有組(無需在此部分中指定順序)。

對於我來說,現在的困難是對話的順序,因為gpMsgeidMsge是孤立的。 我如何排序的time在每個表中的值,並獲得名字theUsertheGroup在表中? 先感謝您!

您可以使用“ 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

UPDATE

完整的查詢將是這樣的:

 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;

DEMO

獲取所有具有特定用戶作為成員且尚未收到消息的組:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM