首先,我是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.
使用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
它应该是
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
我相信你想要的查询看起来像这样:
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
)。