使用员工数据库(https://github.com/datacharmer/test_db)我有(作为示例)以下语句:
select first_name, count(*) from employees;
现在这将给出以下输出:
first_name | count(*)
Georgie | 300024
虽然这个声明:
select first_name, (select count(*) from employees) from employees;
将给出以下输出:
first_name | select count(*) ...
Georgi | 300024
Bezalel | 300024
Parto | 300024
etc... | 300024
澄清我的问题:我不明白为什么第一个语句将我的搜索查询限制为 1 行(只有 Georgi 出现)而最后一个语句(带有子查询)显示所有名称,因此不限制我的搜索查询到 1 行,如第一行。
最佳答案
您的第一个查询:
Count()
是一个聚合函数,它计算数据集(或组)中的所有行。这就是为什么你只得到 1 行的原因,因为你在这里只有一组。
您的第二个查询:
你正在做完全相同的事情(引用第一个查询)但现在你在 subquery
中做它所以它对每一行运行并且它再次是 Count(*)
所以它返回相同的值。
解决方案:
您需要使用Group By
按first_name
在您的数据中进行分组。然后计算
每组中的行数:
Select first_name, count(first_name)
From employee
Group by first_name
它将为您提供数据集中所有 first_name
的计数。
关于mysql - 为什么 count(*) 将我的搜索限制为 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35534540/