select 在 Mysql 中使用计数、分组依据、排序依据和联合失败

Fail to select with count, group by, order by and union in Mysql

我有以下三个表:

theUser(*user_id*, user_name)
ichat(*message_id*, sender, receiver, send_time)
gchat(*message_id*, sender, receiver, send_time)

ichat和gchat的唯一区别是ichat中的receiver是用户,gchat中是组。但对本题没有影响

现在我想找出最活跃的 n 用户(用户名和相应的发送消息数),即在 sender 中出现频率最高的用户。以下是我尝试过的代码:

    SELECT COUNT(totalM.*) AS msge, u.name
    FROM (
        SELECT * FROM gchat
        UNION ALL
        SELECT * FROM ichat) AS totalM
    JOIN theUser u ON totalM.sender=u.user_id
    GROUP BY totalM.sender
    ORDER BY COUNT(*)

但是出现这样的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '*) AS msge, u.name.

你有什么想法吗?提前致谢!

 SELECT COUNT(*) AS msge, u.name
    FROM (
        SELECT * FROM gchat
        UNION ALL
        SELECT * FROM ichat) AS totalM
    JOIN theUser u ON totalM.sender=u.user_id
    GROUP BY u.Name
    ORDER BY COUNT(*)
  1. GROUP BY 应匹配非聚合的 select 列
  2. 我相信引擎无法计算 table 联接的一侧。它在开始计数之前不知道关系是 1-1 还是 1-M,所以它必须计算双方,因此 count(*).

或者您可以将两个计数 (*) 都切换为计数 (1),以获得我相信的相同效果。