Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 简单的sql计数和子查询_Mysql_Sql - Fatal编程技术网

Mysql 简单的sql计数和子查询

Mysql 简单的sql计数和子查询,mysql,sql,Mysql,Sql,我目前正在做一个sql问题 问:使用产品表,找出只生产一种型号的制造商数量 数据库方案由四个表组成: 产品(制造商、型号、类型) “产品”表包括制造商、型号和类型(“PC”、“笔记本电脑”或“打印机”)的相关信息。假设产品表中的型号对于所有制造商和产品类型都是唯一的 查询: select count(maker) from product group by maker having count(model)=1 Select count(*) from (select maker from p

我目前正在做一个sql问题

问:使用产品表,找出只生产一种型号的制造商数量

数据库方案由四个表组成: 产品(制造商、型号、类型)

“产品”表包括制造商、型号和类型(“PC”、“笔记本电脑”或“打印机”)的相关信息。假设产品表中的型号对于所有制造商和产品类型都是唯一的

查询:

select count(maker) from product group by maker having count(model)=1

Select count(*) from (select maker from product group by maker having count(model)=1)as A

我想知道这两个查询之间的区别在我看来是一样的,但第二个查询显然是正确的答案。

让我们看看第一个查询

create table product ( maker int not null, model int not null );
insert into product (maker, model) values (1,1),(1,2),(2,1),(3,1),(4,1),(5,1);

select maker from product group by maker having count(model)=1
MAKER      
-------
      2
      3
      4
      5
i、 e.制造商2,3,4,5正好有一种产品

select count(maker) from product group by maker having count(model)=1
每个制造者发生一个,即

-------
      1
      1
      1
      1
另一方面,另一个查询将计算有多少制造商:

select count(*) from (select maker from product group by maker having count(model)=1)

--------
      4

让我们看一下第一个查询

create table product ( maker int not null, model int not null );
insert into product (maker, model) values (1,1),(1,2),(2,1),(3,1),(4,1),(5,1);

select maker from product group by maker having count(model)=1
MAKER      
-------
      2
      3
      4
      5
i、 e.制造商2,3,4,5正好有一种产品

select count(maker) from product group by maker having count(model)=1
每个制造者发生一个,即

-------
      1
      1
      1
      1
另一方面,另一个查询将计算有多少制造商:

select count(*) from (select maker from product group by maker having count(model)=1)

--------
      4

不,两者都是不同的,第一个会给出每个制造者的计数,第二个会给出你有多少个制造者,第二个会给出一个模式下的所有制造者,结果是一行,你在制造者中有空吗?COUNT(column_name)忽略column_name中的空值,COUNT(星号)提供直接的行计数。如果您将顶部查询更改为COUNT(星号)并获得相同的结果,我敢打赌这就是问题所在。没有两个都不同,第一个将给出每个生成器的计数,第二个将给出多少个生成器,第二个将为所有生成器提供一种模式,并将生成一行生成器中是否有空值?COUNT(column_name)忽略column_name中的空值,COUNT(星号)提供直接的行计数。如果您将顶部查询更改为COUNT(星号)并得到相同的结果,我敢打赌这就是问题所在。