如何在sql中使用order by和group by?

时间:2013-04-21 12:42:47

标签: php sql group-by sql-order-by

这是我的问题: 我有这些表:

felado  fogado  fehide  fohide  datum   olvasott    tartalom

felado =发送者,fogado =接收者,

我想得到felado或fogado在我身上的所有地方并分组。所以如果有下一行

sender 1 receiver 2 id 1
sender 1 receiver 2 id 2
sender 1 receiver 2 id 3
sender 2 receiver 1 id 4

我只想从这些行中获取一个,最后一个是ID。

现在我正在尝试这样:

SELECT * 
FROM belso_levelezes 
WHERE (felado="'.$_SESSION["userData"]["id"].'"
   or fogado="'.$_SESSION["userData"]["id"].'" )
ORDER BY id DESC 
GROUP BY felado, fogado

它只给了我一个,但不是最后的记录。如何从每个组中获取最后的记录? 我想只得到这个:

sender 2 receiver 1 id 4

2 个答案:

答案 0 :(得分:1)

您可以使用子查询创建两个每个对话唯一的列。然后,您可以对这些列进行分组,并获取对话的最大ID。该示例假设您的用户ID为42:

SELECT  sr1
,       sr2
,       max(id)
FROM    (
        SELECT  case when Sender < Receiver then Sender else Receiver end as sr1
        ,       case when Sender > Receiver then Sender else Receiver end as sr2
        ,       id
        FROM    YourTable
        WHERE   42 in (Sender, Receiver)
        ) as SubQueryAlias
GROUP BY
        sr1
,       sr2

答案 1 :(得分:0)

'SELECT MAX(id),felado,fegado,... FROM belso_levelezes WHERE (felado="'.$_SESSION["userData"]["id"].'" or fogado="'.$_SESSION["userData"]["id"].'" ) GROUP BY felado, fogado '