duanjizi9443 2017-04-10 07:06
浏览 32
已采纳

mysql连接两个不同的表

I have two tables in my MySql database:

user    
- sid
- userid
- username

log
- sid
- userid
- login_time

As you can guess, there's a lot more records in log tables than in user table. I am using php to present these records on my website in a table format as shown below.

no  |  userid |  username  |  number of login  |
1   |  inzo   |  harvey    |        233        |
2   |  chae   |  schmidts  |        433        |
3   |  hibro  |  swainy    |        12         |

To get the number of login for each user, I can send another queries in a for statement. But it's consuming resources and making the server slow in the end.

Can I have this result in one single join query?

  • 写回答

4条回答 默认 最新

  • dtcpvz8162 2017-04-10 07:09
    关注

    Yes you can, you have to use count the logins for each user with a group by

    select  t1.userid, t1.username, count(t2.sid)
    from    user t1
    left join
            log t2
    on      t1.userid = t2.userid
    group by t1.userid, t1.username
    

    The left join ensures you that users without logins will still be returned, wit 0 as count.

    Edit

    About the question in the comment: if you want to only count the logins with a specific flag value, you can just add where flag = x before the group by; if you want to have a separate count for each value of the flag, you have to add that flag to both group by and select.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c