加入MySQL表以显示计数

问题描述 投票:0回答:3

首先,我是MySQL的初学者,我还在学习。我正在尝试加入2个表来显示计数。首先,我使用2个代码。显示名称的一个代码 -

SELECT tag_logs.timestamp, People.Name FROM `tag_logs` INNER JOIN People  WHERE tag_logs.tag_no = People.nametag

另一个显示名字数量的代码 -

SELECT tag_logs.tag_no, COUNT(tag_logs.tag_no) FROM tag_logs GROUP BY tag_no HAVING COUNT(tag_no) >= 1

我想显示名称和计数,而不是标签号和计数。我尝试使用以下代码加入这两个表,但是,我没有运气 -

SELECT People.Name FROM `tag_logs` INNER JOIN People  WHERE tag_logs.tag_no = People.nametag AND COUNT(tag_logs.tag_no) FROM tag_logs GROUP BY tag_no HAVING COUNT(tag_no) >= 1

当我尝试第二次调用'FROM tag_logs'时,我收到了一个错误。有办法解决这个问题吗?

I aim to make this my final result, except I should be able to see names instead of numbers.

mysql sql
3个回答
0
投票

使用ON子句连接两个表。你应该学习连接。

SELECT  People.Name ,COUNT(tag_logs.tag_no) 
FROM `tag_logs`
INNER JOIN People  ON tag_logs.tag_no = People.nametag 
GROUP BY tag_logs.tag_no
HAVING COUNT(tag_no) >= 1

0
投票

它应该是

SELECT People.Name FROM `tag_logs`
INNER JOIN People on tag_logs.tag_no = People.nametag
GROUP BY tag_no HAVING COUNT(tag_no) >= 1

编辑

SELECT People.Name, COUNT(tag_no)  FROM `tag_logs`
INNER JOIN People on tag_logs.tag_no = People.nametag
GROUP BY tag_no HAVING COUNT(tag_no) >= 1

0
投票

我相信你想要的查询看起来像这样:

SELECT p.Name, COUNT(*) 
FROM tag_logs tl INNER JOIN
     People p
     ON tl.tag_no = p.nametag 
GROUP BY p.Name;

笔记:

  • COUNT(*)COUNT(tl.tag_no)短,他们做同样的事情。
  • GROUP BY条款现在匹配SELECT。如果您可以拥有相同名称的人,那么将p.nametag添加到GROUP BY。仅使用GROUP BY tl.tag_no的版本是无效的SQL,并且在大多数数据库中都会失败,因为p.Name中的SELECT不匹配。
  • HAVING条款(HAVING COUNT(tag_no) >= 1)是不必要的,因为INNER JOIN需要至少一个匹配,tag_no永远不会NULL(因为它用于JOIN)。
  • 我引入了表别名,因此查询更容易编写和读取。
© www.soinside.com 2019 - 2024. All rights reserved.