0

私はこの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」ごとに1つ(最新)の結果のみを取得したいと思います。(この例では、同じ'from_id'から2つのメッセージを受け取りました-111)

4

4 に答える 4

3

多分GROUP BY

SELECT * FROM chat WHERE `to_id` = '$user_id' AND `from_id` IN($data) GROUP BY  `from_id` ORDER BY `sent` DESC 
于 2012-09-27T08:42:14.180 に答える
1

SELECT * FROM chat WHERE to_id = '$user_id' ANDfrom_idIN($data) GROUP BY from_id order by sent desc

于 2012-09-27T08:41:53.237 に答える
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)
于 2012-09-27T08:45:13.957 に答える
0

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

Order byは最近のメッセージを注文し、LIMIT0,1は1つのメッセージのみを返します。

于 2012-09-27T09:40:41.990 に答える