2013-08-21 44 views
0

我有一個表格用於存儲對話的消息。這是我的查詢:在mysql選擇語句中group by無法正常工作

SELECT 
    a.id, 
    a.`from member_id`, 
    a.`to member_id`, 
    IF(a.`from member_id`={$targetID}, a.`to member_id`, a.`from member_id`) as other_id, 
    a.text, 
    MAX(a.`date sent`) as `date sent`, 
    a.to_read, 
    m.`first name`, 
    m.`last name`, 
    m.avatar_name, 
    m.avatar_status 
    FROM message a 
    JOIN members m on IF(a.`from member_id`={$targetID}, a.`to member_id`, a.`from member_id`) = m.id 
    WHERE (a.`from member_id`={$targetID} OR a.`to member_id`={$targetID}) AND a.active=1 
    GROUP BY IF(a.`from member_id`={$targetID}, a.`to member_id`, a.`from member_id`) 
    ORDER BY `date sent` DESC 

消息表是這樣的:

id    int(11)   id of the message  
from member_id int(11)   id of the person the message was sent from 
to member_id  int(11)   id of the person the message was sent to 
date sent  datetime   date of when it was sent 
active   tinyint(1)  if the message is deleted  
text    longtext  the text of the message 
from_read  tinyint(1)  boolean to know if the person who sent it read it 
to_read   tinyint(1)   boolean to know if the person who it got sent to read it 

這個SELECT語句是用來顯示你目前擁有會話列表。例如,當您點擊Android智能手機上的短信圖標時,您會看到一系列會話,並且每個人都有最近一次在您和另一個人之間交換的消息。

因此,我在選擇語句中做的是獲取消息,其中您的ID在tofrom中,然後對其進行分組,以便使用的行是您與其他人之間交換的最近消息。

問題是,當一個人向他們發送文本自我時,最近的文本不會顯示出來。

有誰知道最新的問題?

謝謝。

回答

0

引述你的問題:

所以我在SELECT語句中我做的是讓地方 您的ID是在或從,則使該行正在使用 組消息您和其他人之間交換的最新消息。

這可能是你想要做的。這不是查詢所做的事情。所述group by子句是:

GROUP BY IF(a.`from member_id`={$targetID}, a.`to member_id`, a.`from member_id`) 

當它遇到滿足條件的多個行,它選擇從那些行範圍字段中的任意order by與選擇最近的消息無關,即使這是你想要的。

拿到兩個發件人之間最近的消息,試試這個:

select least(`from member_id`, `to member_id`) as id1, 
     greatest(`from member_id`, `to member_id`) as id2, 
     max(id) as theid 
from messages m 
group by least(`from member_id`, `to member_id`), 
     greatest(`from member_id`, `to member_id`); 

這將提供最新的消息ID列表(假設他們將按順序分配)。您可以將其加入您的查詢以獲取最新消息。

+0

我不確定我瞭解您的查詢。消息表中的行是來自多個對話的消息。我試圖從該表中獲取特定的行。我想要的每一行都應該是您和其他人之間交換的最新消息。此外,返回行的順序應該排序,以便最近的對話位於最前面。另外,當條件組滿足不止一行時,我嘗試使它選擇最近的一行,因爲我在頂部放了'MAX(a.date sent)'作爲發送日期',所以這不會使通過選擇最近的一個組? – omega

+0

@omega。 。 。你的問題的答案是「不」。如果你想要最近的一個,你需要計算它並加入它。 –