0

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

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
4

2 回答 2

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
于 2013-04-21T13:09:07.547 回答
0
'SELECT MAX(id),felado,fegado,... FROM belso_levelezes WHERE (felado="'.$_SESSION["userData"]["id"].'" or fogado="'.$_SESSION["userData"]["id"].'" ) GROUP BY felado, fogado '
于 2013-04-21T13:10:26.453 回答