在按摩系统中,我想选择用户的所有对话。
我的msg
表格如下:
id | mfrom | mto | date
=========================
1 | 10 | 12 | 0000
2 | 14 | 10 | 0000
3 | 10 | 14 | 0000
4 | 16 | 10 | 0000
5 | 10 | 16 | 0000
这里我的用户ID说:10。如上所述,我有3个用户ID为12,14,16的对话
我使用这个sql让用户ID与我交谈:
$results = mysqli_query($db,"SELECT mfrom FROM msg WHERE `mto`='10' GROUP BY `mfrom` ORDER BY `date` DESC") or die(mysqli_error($db));
while($rows = mysqli_fetch_assoc($results)) {
$mfroms[] = $rows['mfrom'];
}
$results = mysqli_query($db,"SELECT mto FROM msg WHERE `mfrom`='10' GROUP BY `mto` ORDER BY `date` DESC") or die(mysqli_error($db));
while($rows = mysqli_fetch_assoc($results)) {
$mtos[] = $rows['mto'];
}
$result = array_unique(array_merge($mfroms,$mtos), SORT_REGULAR);
上面的查询给了我一个数组结果12,14,16
现在我的问题是,我无法通过小组获取与我的所有对话。这意味着,我想从上表中得到如下结果:
user 12 conversation with user 10(me) total 1 display recent massage only
-------------------------------------------------------------------------
user 14 conversation with user 10(me) total 2 display recent massage only
-------------------------------------------------------------------------
user 16 conversation with user 10(me) total 2 display recent massage only
答案 0 :(得分:1)
将您的表名替换为AccountTable,将10替换为您的用户ID并对其进行测试。
{{1}}
答案 1 :(得分:0)
如果我理解正确的话:
SELECT s.user1,s.user2,count(*) as recent_messages
FROM (
SELECT CASE WHEN t.mfrom > t.mto THEH t.mfrom ELSE t.mto END as user1,
CASE WHEN t.mfrom > t.mto THEH t.mfrom ELSE t.mto END as user2
FROM YourTable t) s
GROUP BY s.user1,s.user2
答案 2 :(得分:0)
这是一种方法:
select (case when m.mfrom = 10 then m.mto else m.mfrom end) as other_user,
10 as me,
count(*),
min(id) as message_id
from messages m
where 10 in (m.mfrom, m.mto)
group by other_user;