简体   繁体   English

mysql连接两个不同的表

[英]mysql join two different tables

I have two tables in my MySql database: 我的MySql数据库中有两个表:

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. 我正在使用php以如下所示的表格格式在我的网站上显示这些记录。

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. 为了获得每个用户的登录数量 ,我可以在for语句中发送另一个查询。 But it's consuming resources and making the server slow in the end. 但这会消耗资源,并最终使服务器变慢。

Can I have this result in one single join query? 我可以在单个联接查询中得到此结果吗?

Yes you can, you have to use count the logins for each user with a group by 是的,可以,您必须使用对每个用户的登录次数进行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. left join确保您仍将返回未登录的用户,计数为0。

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 ; 关于注释中的问题:如果只想计算具有特定标志值的登录数,则只需在group by之前添加where flag = x 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 . 如果要对标志的每个值分别计数,则必须将该标志添加到group byselect

我猜是最好的,我的意思是,最不消耗资源的方法是在用户表中添加“ number_of_login”,并在每次登录时都增加它,因为任何其他解决方案都需要循环

SELECT TABLE_A.row_id, TABLE_A.category, TABLE_A.val_1, TABLE_B.val_2
FROM TABLE_B
LEFT OUTER JOIN TABLE_A ON TABLE_B.row_id = TABLE_A.row_id
ORDER BY row_id;

If you want all the results, you need an outer join, not an inner one. 如果要获得所有结果,则需要一个外部联接,而不是一个内部联接。

从用户a中选择a.sid,a.userid,a.username,COUNT(b.sid)a左连接日志b ON b.sid = a.sid按a.sid分组

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

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