2012-10-09 36 views
2

我正在開發一個聊天工具,並與即時通訊問題與SQL返回正確的結果與組和按順序。該表具有如下所示的結構;Mysql小組按順序給出奇怪的結果

表名:「從」聊天

id | from | to | sent | read | message 

和「到」是一個帶符號的整數(用戶ID) 「發送」是時間戳被髮送的消息時。 'message'is text msg 'read'是一個int(0表示未讀,1表示讀取)。

我嘗試返回用戶

例如分組最近的消息列表

id   from  to  message  sent read 
7324  21  1  try again 1349697192 1 
7325  251  1  yo whats up 1349741502 0 
7326  251  1  u there  1349741686 0 

查詢

id  from to  message  sent  read 
7326  251  1  u there 1349741686 0 
7324  21  1  try again 1349697192 1 

這裏後應該返回,這是我的查詢

$q ="SELECT chat.to,chat.read,chat.message,chat.sent,chat.from FROM `chat` WHERE chat.to=$userid GROUP BY chat.from ORDER BY chat.sent DESC,chat.read ASC LIMIT ".(($page-1)*$count).",$count";    

它不會返回所需的結果;

回答

3

您應該創建一個子查詢,它將通過users確定最新的sent,然後使用chat表將其加入。

SELECT a.*     -- this will list all latest rows from chat table 
FROM `chat` a 
     INNER JOIN 
     (
      SELECT `from`, `to`, MAX(sent) maxSent 
      FROM `chat` 
      GROUP BY `from`, `to` 
     ) b ON a.`from` = b.`from` AND 
       a.`to` = b.`to` AND 
       a.sent = b.maxSent 
-- WHERE ....     -- add your condition(s) here 

SQLFiddle Demo

+0

在查詢中,我沒有看到,你可以指定「到」例如,在我的例子$用戶ID的一部分。檢查瞭解我的意思http://sqlfiddle.com/#!2/ca5a0/1 –

+0

此外,未讀,即閱讀= 0應顯示之前閱讀= 1 –

+0

@SirLojik [看到這個:添加在哪裏和訂單BY條款](http://sqlfiddle.com/#!2/ca5a0/5) –