2013-10-16 100 views
0

我打算與相對的最後一條消息進行對話,並按時間排序,如果是讀取消息。讓我們去展示我的邏輯。獲取對話和最後一條消息查詢

我在3臺:inbox_join/inbox_msg /用戶

在第一表「收件箱加盟」我對誰擁有積極討論的DATAS。在這種情況下,我們有id_user - 「1」和id_user_2 - 「4」他們有一個對話。

在inbox_msg表中我有文本消息,id對話,其中消息將顯示,其他字段易於理解。

收件箱連接表

enter image description here

Inbox_msg表 enter image description here

用戶表

enter image description here

我做了做工精細的查詢,但我的問題是,我inbox_msg表中不能包含occured_at。我想找到一個更好的解決方案,讓我的願望結果,我不能命令我在找什麼。

這是我的查詢

SELECT DISTINCT (
inbox_join.id_conversation 
), user_chat.name AS name_conv, user_chat.surname AS surname_conv, user_chat.username as username_conv, user_chat.id as id_chat, image_upload.name_image, (

SELECT DISTINCT (
message 
) 
FROM inbox_msg 
WHERE inbox_join.id_conversation = inbox_msg.id_conversation 
ORDER BY occured_at DESC 
LIMIT 1 
) AS last_msg, users.name, users.surname 
FROM inbox_join 

INNER JOIN users ON users.id = inbox_join.id_user 
INNER JOIN users AS user_chat ON user_chat.id <> 1 AND (inbox_join.id_user_2 = user_chat.id || inbox_join.id_user = user_chat.id) 
INNER JOIN image_upload ON image_upload.id_image = user_chat.profile_image 
WHERE inbox_join.id_user = 1 
OR inbox_join.id_user_2 = 1 

結果desidered選擇圍繞用戶1的對話:

id_conversation | id_user | name | surname | username | last_msg | occured_at_last_msg | read_msg | 

     1   4   E  S   E   Yes   1380724676  0 
     4   5   G  E   K   Good   1380724675  0 

回答

-1

我做了這個查詢,並應做工精細,我想收到有關該查詢的評論。

SELECT DISTINCT (
      im.id_conversation 
      ), users.name, users.surname, users.username, image_upload.name_image, im.message as last_msg, im.occured_at, im.read_msg 
      FROM inbox_join 
      INNER JOIN (

      SELECT sub . * 
      FROM (

      SELECT DISTINCT (
      id_conversation 
      ), id_user, message, occured_at, read_msg 
      FROM inbox_msg 
      WHERE id_user <> 1 
      ORDER BY occured_at DESC 
      ) AS sub 
      GROUP BY sub.id_user 
      ORDER BY sub.occured_at DESC 
      ) AS im ON im.id_conversation = im.id_conversation 
      INNER JOIN users ON im.id_user = users.id 
      INNER JOIN image_upload ON users.profile_image = image_upload.id_image 
      WHERE inbox_join.id_user = 1 || inbox_join.id_user_2 = 1 
+0

HM這是一個混亂的類.. GROUP BY子句中沒有列名,ORDER BY子句中的子查詢中得到什麼? – Justin

1

查詢:

SELECT im.id_conversation, 
     im.id_user, 
     u.name, 
     u.surname, 
     u.username, 
     im.message AS last_msg, 
     im.occured_at AS occured_at_last_msg, 
     im.read_msg 
FROM inbox_msg im 
JOIN users u 
ON u.id_user = im.id_user 
JOIN (SELECT id_conversation, 
      MAX(occured_at) AS occured_at 
     FROM inbox_msg 
     GROUP BY id_conversation) im2 
ON im2.id_conversation = im.id_conversation 
AND im2.occured_at = im.occured_at 
ORDER BY im.occured_at DESC 
相關問題