MySQL: 关联 5 个表 LEFT JOIN 和 COUNT

MySQL: Relate 5 tables LEFT JOIN and COUNT

我有 5 张桌子:

其中 usuario 可以将 productos 添加为 favoritoslikes chistes。我有兴趣了解同一查询中每个 usuariofavoritoslikes 的总数,并按一个或另一个数量对 usuarios 列表进行排序(favoritoslikes 的数量,具体取决于选择的内容)。我知道如何分别进行,即在两个不同的查询中:

SELECT usuarios.*,
count(favoritos.id_usuario) AS numFavoritos
FROM usuarios
LEFT JOIN favoritos 
ON usuarios.id_usuario = favoritos.id_usuario
GROUP BY usuarios.id_usuario
ORDER BY numFavoritos DESC
SELECT usuarios.*,
count(likes.id_usuario) AS numLikes
FROM usuarios
LEFT JOIN likes 
ON usuarios.id_usuario = likes.id_usuario
GROUP BY usuarios.id_usuario
ORDER BY numLikes DESC

我一直试图在单个数据库查询中完成它,但我做不到。 如果有人能提供帮助,我将不胜感激,向大家问好!

针对新要求的更新答案

But I have a problem with this, when a usuario does not have any likes or favoritos, it does not do the sum of total_interaction well, because the value of total_likes or total_favoritos is null. How can I do it?

简单地用COALESCE()操作解决你的if null return 0,它将return the first non-null value in the list

我们将把表达式likes_stats.total_likes包装成

COALESCE(likes_stats.total_likes, 0)

意味着如果 likes_stats.total_likes 为 NULL,将返回 0

完整查询

SELECT u.id_usuario, u.nombre_usuario, 
COALESCE(likes_stats.total_likes, 0) as total_likes, 
COALESCE(favoritos_stats.total_favoritos, 0) as total_favoritos,
COALESCE(likes_stats.total_likes, 0) + COALESCE(favoritos_stats.total_favoritos, 0) as total_interaction
FROM usuarios u
-- joining with the like count group by each user
LEFT JOIN 
(SELECT CASE WHEN COUNT(*) IS NOT NULL THEN COUNT(*) ELSE 0 END as total_likes, id_usuario FROM likes
GROUP BY id_usuario) likes_stats ON u.id_usuario = likes_stats.id_usuario
-- joining with the favourite count group by each user
LEFT JOIN 
(SELECT COUNT(*) as total_favoritos, id_usuario FROM favoritos
GROUP BY id_usuario) favoritos_stats ON u.id_usuario = favoritos_stats.id_usuario
ORDER BY likes_stats.total_likes DESC;
id_usuario nombre_usuario total_likes total_favoritos total_interaction
2 manolo garcia 1 2 3
1 jose perez 1 1 2
3 antonio sanchez 1 1 2
4 manali tagret 0 0 0

说明
您将需要加入用户 table 和每个用户的两个额外统计计数 table,以及每个用户的收藏。

每人点赞table(别名likes_stats)给你每个人的点赞数

SELECT COUNT(*) as total_likes, id_usuario FROM likes
GROUP BY id_usuario
total_likes id_usuario
1 1
1 2
1 3

每个常用词的收藏夹table(别名favoritos_stats)给你每个常用词的收藏夹数量

SELECT COUNT(*) as total_favoritos, id_usuario FROM favoritos
GROUP BY id_usuario
total_favoritos id_usuario
1 1
2 2
1 3

然后我们简单地加入三个table:usuariolikes_statsfavoritos_stats id_usuario

您可以按自己喜欢的顺序排序,或按likes_stats.total_likes收藏,或favoritos_stats.total_favoritos

我还添加了total_interaction,这是总喜欢和喜欢的总和,以防你想按喜欢和喜欢的总数一起排序,只是为了方便。

这是SQL fiddle for the test schema you provided