group by在mysql select语句中无法正常工作

时间:2013-08-21 18:01:34

标签: php mysql select

我有一张表用于存储会话消息。这是我的问题:

  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智能手机上的短信图标时,您会看到一个对话列表,每个人都有您和另一个人之间交换的最新消息。这就是您所获得的活动。

所以我在select语句中做的是获取你的id在tofrom中的消息,然后对它进行分组,以便正在使用的行是最近交换的消息你和另一个人。

问题在于,当一个人向他们发送文本时,最新的文本不会显示。

有谁知道这个问题是什么?

感谢。

1 个答案:

答案 0 :(得分:0)

引用你的问题:

  

所以我在select语句中所做的就是获取消息   您的id位于to或from中,然后将其分组以便使用该行   是你和另一个人之间交换的最新消息。

这可能是你想要做的。这不是查询正在做的事情。 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的列表(假设它们按递增顺序分配)。您可以将其加入到查询中以获取最新消息。