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在to
或from
中,然後對其進行分組,以便使用的行是您與其他人之間交換的最近消息。
問題是,當一個人向他們發送文本自我時,最近的文本不會顯示出來。
有誰知道最新的問題?
謝謝。
我不確定我瞭解您的查詢。消息表中的行是來自多個對話的消息。我試圖從該表中獲取特定的行。我想要的每一行都應該是您和其他人之間交換的最新消息。此外,返回行的順序應該排序,以便最近的對話位於最前面。另外,當條件組滿足不止一行時,我嘗試使它選擇最近的一行,因爲我在頂部放了'MAX(a.date sent)'作爲發送日期',所以這不會使通過選擇最近的一個組? – omega
@omega。 。 。你的問題的答案是「不」。如果你想要最近的一個,你需要計算它並加入它。 –