我想从SentBy和SentTo的组合中选择最大ID 我的意思是我希望组(SentTo-SentBy)如1-3和3-1组合在一起..类似1-2和2-1也应该组合在一起
查询是什么?
用户:
**ID | Name**
1 | A
2 | B
3 | C
4 | D
聊天
ID | Msg | SentBy (Users.ID) | SentTo (Users.ID)
1 | abc | 1 | 2
2 | def | 1 | 3
3 | ghi | 1 | 4
4 | jkl | 2 | 1
5 | mno| 2 | 1
6 | pqr | 3 | 1
7 | stu | 3 | 1
8 | vwx| 4 | 1
9 | yz | 4 | 1
10| def | 1 | 3
12| jkl | 2 | 1
必需
ID | Msg | SentBy (Users.ID) | SentTo (Users.ID)
3 | ghi | 1 | 4
10| def | 1 | 3
12| jkl | 2 | 1
答案 0 :(得分:1)
使用LEAST()
和GREATEST()
<强> Sql Fiddle Demo 强>
SELECT Chat.*
FROM Chat
JOIN (
SELECT MAX(`ID`) m_value
FROM Chat
GROUP BY LEAST(`SentBy`, `SentTo`) , GREATEST(`SentBy`, `SentTo`)
) C
ON Chat.`ID` = C.m_value
<强>输出强>
| ID | Msg | SentBy | SentTo |
|----|-----|--------|--------|
| 9 | yz | 4 | 1 |
| 10 | def | 1 | 3 |
| 12 | jkl | 2 | 1 |
答案 1 :(得分:0)
我认为你正在寻找这个
select max(id) from chat as c1
inner join chat as c2 on (c1.sent_by = c2.sent_to and c1.sent_to = c2_sent_by)
group by c1.sent_by, c1.sent_to ;