简体   繁体   English

从一个表的MySQL Count,联接到另一个表

[英]MySQL Count from one table, join to another table

Here's what I'm trying to do: Table A has a record of user logins Table B has the user's information 这是我要执行的操作:表A记录了用户登录信息表B显示了用户信息

I want to computer the total number of logins for each user in table A, then join that to table B so my outcome is something like.... 我想计算表A中每个用户的登录总数,然后将其加入表B中,所以我的结果类似于...。

User 1 Name: John Logged In: 15 times User 2 Name: Mary Logged In: 22 times 用户1名称:John登录:15次用户2名称:Mary登录:22次

Any help is greatly appreciated 任何帮助是极大的赞赏

You need something like that: 您需要这样的东西:

SELECT u.*, count(l.id) AS login_count
FROM user s
LEFT JOIN login l ON u.id = l.user_id
GROUP login.id
SELECT
    users.*,
    COUNT(user_logins.user_id) as login_count
FROM users 
LEFT JOIN user_logins ON user_logins.user_id = users.user_id
GROUP BY users.user_id

If you don't need the users with 0 logins remove LEFT from the LEFT JOIN 如果您不需要0登录的用户,请从LEFT JOIN删除LEFT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM