MySQL:连接三个表并显示总数

标签 mysql sql

我有以下三个表格(简化):

User ( 
    UserID
    UserName
) 

UserMsg ( 
   toUserID
    MsgID
   theMsg

)

UserMsgComment ( 
   CommentID, 
  MsgID, 
 theComment 
) 

并且想要显示每个用户拥有的 UserMsg-s 以及每个 UserMsg 的 UserMsgComment 的计数。如果 UserMsg 没有 UserMsgComment,我想显示“0”。

  UserName | UserMsg | COUNT(UserMsgComment) or show '0' 


SELECT u.*, m.theMsg FROM User u, 
LEFT JOIN UserMsg m ON u.UserID = m.toUserID 

如何修改此查询以显示每个 UserMsg 的 UserMsgComment 总数,或者如果 UserMsgComment 中没有条目,则显示 0?

非常感谢。

最佳答案

您只需加入额外的 table 并相应地分组即可。请注意,如果您想选择 u.*,则还必须按用户表中的每一列进行分组。

SELECT u.UserID, m.theMsg, COUNT(mc.CommentID)
FROM User u, 
LEFT JOIN UserMsg m ON u.UserID = m.toUserID
LEFT JOIN UserMsgComment mc on m.MsgID = mc.MsgID
GROUP BY u.UserID, m.theMsg

关于MySQL:连接三个表并显示总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18384501/

相关文章:

mysql - 基于 2 列的重复行的 SQL 查询

数据库中的 SQL Server 对象

sql - 名字或姓氏大小写更改查询,不会产生意外后果。

sql - MySQL REGEXP 到 SQL Server

python - 如何通过 Python 将 🍒 添加到我的 VARCHAR 字段

mysql - MYISAM 分片与使用 InnoDB

sql - Mysql Count(*) as Total WHERE 总计?

mysql - 使用 MySQL 选择查询以随机顺序对特定数据组的记录进行排序

sqlite元组比较

sql - SQL WHERE IN 子句中的多个键