gpt4 book ai didi

sql - 为什么即使我更改函数 COUNT() 中的参数,结果总是相同?

转载 作者:行者123 更新时间:2023-12-04 18:20:51 26 4
gpt4 key购买 nike

无论函数 COUNT() 的括号内有什么参数,下面三个代码片段的结果都是一样的,为什么?

SELECT Category.Category, Category.CategoryID, COUNT(Category) AS Popularity
FROM FavCategory INNER JOIN Category
ON FavCategory.CategoryID= Category.CategoryID
GROUP BY Category, Category.CategoryID
HAVING COUNT(FavCategory.MemberID)>=2;

SELECT Category.Category, Category.CategoryID, COUNT(FavCategory.CategoryID) AS Popularity
FROM FavCategory INNER JOIN Category
ON FavCategory.CategoryID= Category.CategoryID
GROUP BY Category, Category.CategoryID
HAVING COUNT(FavCategory.CategoryID)>=4;

SELECT Category.Category, Category.CategoryID, COUNT(FavCategory.MemberID) AS Popularity
FROM FavCategory INNER JOIN Category
ON FavCategory.CategoryID= Category.CategoryID
GROUP BY Category, Category.CategoryID
HAVING COUNT(FavCategory.MemberID)>=2;

SELECT Category.Category, Category.CategoryID, COUNT(FavCategory.MemberID+Category.CategoryID) AS Popularity
FROM FavCategory INNER JOIN Category
ON FavCategory.CategoryID= Category.CategoryID
GROUP BY Category, Category.CategoryID
HAVING COUNT(FavCategory.MemberID)>=2;

这是 Category 和 FavCategory 表上的记录
enter image description here

最佳答案

你在问为什么。它们都是一样的,如 COUNT计数取决于字段/表达式是否为空或空。如果值不为空,COUNT计算它;如果为空,则忽略它

您的表上没有任何空值,因此所有三个查询都报告相同的值。试试 COUNT('DRACULA') , COUNT(42) , COUNT(0)甚至COUNT(-1) ,他们将计数 CategoryID 3 为 3,CategoryID 1 为 2 ,它们的工作方式与您的三个查询相同。

当然,您也可以使用 COUNT(*)如果您使用 INNER JOIN , 它是 advisable .如果您使用 LEFT JOIN , 使用 COUNT(*) 是不正确的,您必须这样做:COUNT(secondTable.foreignKeyColumnHere) ;或者如果 Access 支持基于基数的计数(如在 Postgresql 中),只需执行以下操作:COUNT(secondTable.*)
有关正确使用计数和启蒙的入门知识(插头警报),请阅读我关于计数的帖子 http://www.ienablemuch.com/2010/04/debunking-myth-that-countdracula-is.html

@JDein

鉴于此数据:

create table Person
(
PersonId int not null primary key,
Name varchar(100) not null,
Middlename varchar(100) null
);

insert into Person(PersonId,Name,MiddleName) values
(1,'John','Winston'),
(2,'Paul','James'),
(3,'George',NULL),
(4,'Ringo','Parkin');

所有这些都将返回 4:
select count(PersonID) from Person;

select count(Name) from Person;

select count(*) from Person;

select count(1) from Person;

select count(0) from Person;

select count(2) from Person;

select count(-1) from Person;

select count(42) from Person;

select count('Dracula') from Person;

除以下内容外,这将返回 3:
select count(MiddleName) from Person;

现场测试: http://www.sqlfiddle.com/#!3/c1b1e/8

关于sql - 为什么即使我更改函数 COUNT() 中的参数,结果总是相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10714181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com