2017-03-11 76 views
-1

我有我想要顯示像Facebook消息的消息應用程序,它應該由發送者或接收者獲取最後發送的消息,我的表佈局是這樣的:獲取用戶之間的最後一條消息,如Facebook

messages_tbl

__________________________________________________________________________ 
|id | user1Fk| user2Fk |subject | user1Delete | user2Delete | dateCreated | 

和我user_tbl

_______________________________________ 
| id | first_name | last_name | image | 

我查詢

SELECT `id` , `user1Fk` as sender_id, 
     (SELECT concat(first_name,\" \",last_name) 
     FROM user_tbl 
     WHERE user_tbl.id = sender_id 
     ) as senderName, 
     `user2Fk` as recipient_id , 
     (SELECT concat(first_name,\" \",last_name) 
     FROM user_tbl 
     WHERE user_tbl.id = recipient_id 
     ) as recipientName, 
     (SELECT image 
     FROM user_tbl 
     WHERE user_tbl.id = sender_id 
     ) as senderImage, 
     (SELECT image 
     FROM user_tbl 
     WHERE user_tbl.id = recipient_id 
     ) as recipientImage, 
     `subject`, `message`, `user1Delete`, `user2Delete`, 
     `dateCreated` 
    FROM `message_tbl`as m1 
    WHERE dateCreated = (SELECT MAX(m2.dateCreated) 
         from message_tbl as m2 
         WHERE (m1.user1Fk = m2.user1Fk 
           AND m1.user2Fk = m2.user2Fk 
           OR m1.user1Fk = m2.user2Fk 
           AND m1.user2Fk = m2.user1Fk 
          ) 
         ) AND ? IN (m1.user1Fk, m1.user2Fk) 
    ORDER BY dateCreated DESC 

此查詢工作的大部分,但其缺乏的,我想它來檢查,如果由?比賽user1Fk定id應該再檢查,如果user1Delete是0或1,如果一個1然後做不顯示消息user 1刪除它,與用戶2相同,但我想不到的邏輯,任何人都可以幫助我嗎?

+0

類似於https://stackoverflow.com/questions/42740768/mysql-distincs-entry-of-two-columns-even-when-switched/42740903#42740903 – Gab

+0

差不多,但我的已經可以選擇了,我只需要幫助檢查消息是否已被刪除,然後返回 –

回答

0

我假設問號出現了,因爲這是一個準備好的查詢,問號應該用用戶ID替換。

由於有很多子選擇,因此您的查詢有點複雜。爲了獲得更好的性能,我試圖改進它以便能夠更輕鬆地進行擴展。使用SQL,您可以連接表而不是使用子查詢,這對性能更好,並且可以更輕鬆地爲連接的表添加條件。

在下面的示例中,我將user1和user2刪除字段的條件都添加爲0.我將限制設置爲1,這意味着只返回第一行。與日期的降序一起,這意味着只有最新的消息纔會被返回。我還將問號更改爲:user_id,因爲在此示例中它使用了兩次,這樣您只需添加一次即可。

SELECT 
    m.id, 
    u1.id AS sender_id, 
    CONCAT(u1.first_name, ' ', u1.last_name) AS senderName, 
    u2.id AS recipient_id, 
    CONCAT(u2.first_name, ' ', u2.last_name) AS recipientName, 
    u1.image AS senderImage, 
    u2.image AS recipientImage, 
    m.subject, 
    m.message, 
    m.user1Delete, 
    m.user2Delete, 
    m.dateCreated 
FROM messages_tbl m 
INNER JOIN user_tbl u1 ON m.user1Fk = u1.id 
INNER JOIN user_tbl u2 ON m.user2Fk = u2.id 
WHERE (m.user1Delete = 0 AND u1.id = :user_id) 
OR (m.user2Delete = 0 AND u2.id = :user_id) 
ORDER BY m.dateCreated DESC 
LIMIT 1 

我還沒有能夠測試它,但我希望這是你在找什麼。

+0

查詢是好的,但是在user1delete爲1的情況下,即使user1 id不是給定的ID,也不會顯示消息 –

+0

啊對。那這個呢? WHERE(m.user1Delete = 0和u1.id =:USER_ID) OR(m.user2Delete = 0和u2.id =:USER_ID) ORDER BY m.dateCreated DESC LIMIT 1 – Asperitas

+0

這工作,糾正你的回答,我標記它。 –

相關問題