mysql - Sql 按组选择所有对话

标签 mysql sql

在按摩系统中,我想选择用户的所有对话。

我的 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。如上所述,我与用户 ID 12、14、16 进行了 3 次对话

我使用此 SQL 来获取与我对话的用户 ID:

$results = mysqli_query($db,"SELECT mfrom FROM msg WHERE `mto`='10' GROUP BY `mfrom` ORDER BY `date` DESC");
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");
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

最佳答案

将 AccountTable 替换为您的表名称,将 10 替换为您的用户 ID 并进行测试。

SELECT s.user1,s.user2,count(*) as recent_messages
FROM (
    SELECT CASE WHEN t.mfrom > t.mto THEN t.mfrom ELSE t.mto END as user1,
           CASE WHEN t.mfrom < t.mto THEN t.mfrom ELSE t.mto END as user2
    FROM AccountTable t WHERE t.mfrom = 10 OR t.mto=10) s
GROUP BY s.user1,s.user2

关于mysql - Sql 按组选择所有对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40018091/

相关文章:

sql - 选择进入表计数

PHP 循环和 MySQL 中的绑定(bind)查询

MySQL函数仅在未使用传递的参数时才起作用?

mysql - MVC 不返回 json...请求不可用

php - 将 JSON 数据存储为平面文件或数据库

sql - Group by/Distinct Sequelize 查询功能

sql - 动态 SQL PostgreSQL

SQL Server : Select Top 0?

mysql - 如何使用 join 和 group by 获取 Rails 中最后输入的记录字段?

MYSQL多表求和使用主键