在MySQL聊天 - 选择 - GROUP BY

时间:2017-03-17 14:16:31

标签: mysql sql select group-by distinct

我有这些表格:

表名: user_data

---------------------------
| id | owner |    name    |
---------------------------  
|  1 |  120  |  "Nicolas" |   
|  2 |  140  |   "Angel"  |
---------------------------

表名: private_messages

--------------------------------------------
| id | ownerID | toUserID | message        |
--------------------------------------------  
|  1 |   120   |   140    | "Hi"           |
|  2 |   120   |   140    | "How are you?" |
|  3 |   120   |   140    | "I miss u"     |
|  4 |   140   |   120    | "Viewed."      |
--------------------------------------------

我需要为用户选择所有行聊天,例如,我有用户ID“120”,我需要进行一个查询,返回所有在ownerID或者UI中出现“120”的聊天。

这是我的实际查询:

SELECT
user_data.owner,
ANY_VALUE(user_data.name) name,
ANY_VALUE(private_messages.message) message
FROM private_messages 
INNER JOIN user_data ON private_messages.ownerID = user_data.owner 
WHERE private_messages.owner = "120" OR private_messages.toUserID = "120"
GROUP BY user_data.owner

此查询的结果是:

----------------------------------------
| owner |    name     |    message     |
----------------------------------------  
|  120  |  "Nicolas"  |     "Hi"       |
|  140  |   "Angel"   |   "Viewed."    |
----------------------------------------

但是如果你认为,这是错误的,因为这两个元素来自同一个聊天。正确的结果应该是两个用户之间的最后一条消息:

----------------------------------------
| owner |    name     |    message     |
----------------------------------------
|  140  |   "Angel"   |   "Viewed."    |
----------------------------------------

有办法吗?

3 个答案:

答案 0 :(得分:0)

SELECT
user_data.owner,
ANY_VALUE(user_data.name) name,
ANY_VALUE(private_messages.message) message
FROM private_messages 
INNER JOIN user_data ON private_messages.owner = user_data.owner 
WHERE private_messages.touser = "120"
GROUP BY user_data.owner

答案 1 :(得分:0)

    SELECT private_messages.id, user_data.owner,
ANY_VALUE(user_data.name) name,
ANY_VALUE(private_messages.message) message
FROM private_messages 
INNER JOIN user_data ON private_messages.ownerID = user_data.owner 
WHERE private_messages.owner = "120" OR private_messages.toUserID = "120"
GROUP BY user_data.owner order by private_messages.id DESC LIMIT 1

您将获得一个额外的列。我希望您能过滤查询以排除ID行。

答案 2 :(得分:0)

试试这个:

select u.owner, u.name, p.message
from private_messages p 
left join user_data u 
  on p.ownerid = u.owner
where p.id = (select MAX(id) id 
              from private_messages 
              where (ownerid = u.owner or touserId = u.owner) 
                and ownerid = 140 )