doumengyin0491 2013-09-16 16:22
浏览 38
已采纳

MySQL查询计数多个表

At the moment, we have 3 queries. In php, we loop over the first, then execute the 2nd multiple times, then which I'd like to have in one single query:

The first query is:

SELECT id FROM users

Then inside looping over those results, the 2nd is

SELECT id AS rid, count(recommendedById) FROM users WHERE id=$id

where $id is users.id from the first query.

The 3rd query is which is executed inside the 2nd loop is:

SELECT count(likes) AS likeCounter FROM posts WHERE author_id=$rid

and likeCounter is summed up to the first query.

Anyone able to bring this into one query?

Desired result The result should be a row per user with a count of users he recommended and a sum of likes his recommended users got on their posts.

  • 写回答

2条回答 默认 最新

  • duan_88598 2013-09-16 16:33
    关注
    SELECT u.id,COUNT(DISTINCT ruid),sum(p.likes)
    FROM users as u
    LEFT JOIN (SELECT recommendedById as rid,id as ruid from users) as r ON r.rid = u.id
    LEFT JOIN posts p ON p.author_id = ruid
    GROUP BY u.id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器