显示GROUP成员' COUNT没有实际的GROUPing

时间:2014-06-20 16:04:53

标签: mysql sql count group-by

我想显示用户自上次在线活动以来的新消息。这是我目前的查询:

SELECT 
    from_user_id, 
    to_user_id, 
    from_user_id + to_user_id AS combined_key, 
    chat_date, 
    last_activity, 
    message, 
    username, 
    city
FROM chat AS c JOIN users AS u ON (c.from_user_id = u.id)
WHERE (from_user_id = '4' OR to_user_id = '4') AND chat_date > '2014-06-19 00:00:00.0'
ORDER BY combined_key ASC, chat_date ASC

...产生以下结果: enter image description here

现在我想添加一个列,该列在每行中显示具有相同 combined_key 的消息数,因此该小计列将例如在前三行中显示 3 (因为有3条消息带有 combined_key'9')。

类似

SELECT 
    COUNT(*) AS subtotal, 
    from_user_id, 
    to_user_id, 
    from_user_id + to_user_id AS combined_key, 
    chat_date, 
    last_activity, 
    message, 
    username, 
    city
FROM chat AS c JOIN users AS u ON (c.from_user_id = u.id)
WHERE (from_user_id = '4' OR to_user_id = '4') AND chat_date > '2014-06-19 00:00:00.0'
GROUP BY combined_key

...但没有实际分组,从而消除了一些行: enter image description here

2 个答案:

答案 0 :(得分:1)

您需要做的就是在select语句中添加一个子选择。在sql中,您可以在任何位置添加子选择。我们将返回数据,而不是在子选择中比较信息或创建表。您可能需要编辑此子选择以使用您的规范(例如,您可能希望在where子句中指定聊天日期)。此外,根据连接如何影响返回的行,您可能还需要在子选择中包含连接。你必须尝试一些东西看看!使用原始查询:

SELECT (Select count(1)
          from chat c2
          where c2.combined_key = c.combined_key
          Group by c2.combined_key) as subtotal,
      from_user_id,
      to_user_id,
      from_user_id + to_user_id AS combined_key,
      chat_date,
      last_activity,
      message,
      username,
      city
 FROM chat AS c JOIN users AS u ON (c.from_user_id = u.id)
 WHERE (from_user_id = '4' OR to_user_id = '4') AND chat_date > '2014-06-19 00:00:00.0'
 ORDER BY combined_key ASC, chat_date ASC

答案 1 :(得分:-1)

好的,谢谢你的贡献,我终于做到了:

SELECT from_user_id, 
to_user_id, 
from_user_id + to_user_id AS combined_key,
(
  SELECT 
    COUNT(*)
  FROM chat AS c JOIN users AS u ON (c.from_user_id = u.id)
  WHERE (from_user_id = '4' OR to_user_id = '4') AND chat_date > '2014-06-19 00:00:00.0' AND (from_user_id + to_user_id) = combined_key
  ) AS subtotal,

chat_date, 
last_activity, 
message, 
username, 
city
FROM chat AS c JOIN users AS u ON (c.from_user_id = u.id)
WHERE (from_user_id = '4' OR to_user_id = '4')
ORDER BY combined_key ASC, chat_date ASC

enter image description here