SQL如何从每个值中只获得一个结果

时间:2012-09-27 08:40:07

标签: php sql

我有这个SQL查询:

$result = mysql_query("SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id`   IN($data)") or die(mysql_error());
    while ($row = mysql_fetch_assoc($result)) {
    print_r($row);
}

返回此数组:

Array ( [id] => 3505 [from_id] => 111 [to_id] => 109 [message] =>How are you? [sent] =>          1343109753 [recd] => 1 [system_message] => no )    
Array ( [id] => 3506 [from_id] => 111 [to_id]   => 109 [message] =>well... [sent] =>   1343109759 [recd] => 1 [system_message] => no ) 
Array ( [id] => 3507 [from_id] => 141 [to_id] => 109 [message] => bye [sent] => 1343901524 [recd] => 1 [system_message] => no )

From_id是发送邮件的人的用户ID,但我希望每个'from_id'只获得一个(最新的)结果。 (在这个例子中,我从同一个'from_id' - 111获得了2条消息)

4 个答案:

答案 0 :(得分:3)

也许GROUP BY

SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data) GROUP BY  `from_id` ORDER BY `sent` DESC 

答案 1 :(得分:1)

SELECT * FROM chat WHERE to_id = '$user_id' AND {from_id {1}}

答案 2 :(得分:0)

尝试这样的事情,

SELECT a.*
FROM chat a INNER JOIN
        (
           SELECT   from_id, to_id ,MAX(sent) maxSent
           FROM     chat
           GROUP BY from_id, to_id
        ) b ON a.from_id = b.from_id AND
                a.to_id = b.to_id AND
                a.sent = b.maxSent
WHERE `to_id` = '$user_id' AND 
        `from_id` IN ($data)

答案 3 :(得分:0)

SELECT * FROM chat WHERE to_id ='$ user_id'AND from_id IN($ data)order by sent desc limit 0,1

按顺序排序最近的messgae和LIMIT 0,1只会返回一条消息。