简体   繁体   English

试图计数并加入两个mysql表

[英]trying to count and join on two mysql tables

I've got a mysql db with two tables: 我有一个带有两个表的mysql数据库:

db.names db.names

name | Level
------------
bob    4
john   3
andy   2
dave   1

db.data db.data

entry | user
------------
dfds    bob
hdes    bob
sers    john
iuid    dave
yyuy    john

I'm trying to do a count that will count how many entrys each user has made and also show their level. 我正在尝试做一个计数,该计数将计算每个用户所做的条目数并显示其级别。 So lit looks something like this: 如此点亮看起来像这样:

count(*) | user | Level
-----------------------
2         bob     4
2         john    3
1         dave    1

I've tried to use left join and distinct join, but can seem to get to grips with the logic. 我尝试使用左联接和不同联接,但是似乎可以掌握逻辑。 Help would be greatlly appreciated 帮助将不胜感激

You need to basically joins the tables using INNER JOIN since you only want to show a record that both exist on the two tables. 您基本上需要使用INNER JOIN联接表,因为您只想显示两个表中都存在的记录。 And to count their number of instances, you need to use an aggregate function COUNT() and a GROUP BY clause. 为了计算实例数,您需要使用聚合函数COUNT()GROUP BY子句。

SELECT  COUNT(*) TotalCount,
        a.Name,
        a.Level
FROM    names a
        INNER JOIN data b
            ON a.Name = b.user
GROUP   BY a.Name, a.Level

To further gain more knowledge about joins, kindly visit the link below: 要进一步获得有关联接的知识,请访问以下链接:

OUTPUT OUTPUT

╔════════════╦══════╦═══════╗
║ TOTALCOUNT ║ NAME ║ LEVEL ║
╠════════════╬══════╬═══════╣
║          2 ║ bob  ║     4 ║
║          2 ║ john ║     3 ║
║          1 ║ dave ║     1 ║
╚════════════╩══════╩═══════╝

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

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