Home >Backend Development >PHP Tutorial >PHP mysql如何查询某个字段有多少个不同的值

PHP mysql如何查询某个字段有多少个不同的值

WBOY
WBOYOriginal
2016-06-23 13:01:571676browse

举个例子,
在car表有个pinpai字段,
有Lambo,Audi,BMW,Audi,Toyota,Lambo 6个值,
那么这个字段有4个不同的品牌,6辆车
求解如何得出4这个值和6这个值
前台显示的是:"现共有4种品牌车辆,共计6辆。"
-------------------------------------------------------------------------

求大神给个完整的sql select语句 本人新手求实力老司机指点
--------------------------------------------------------------------------
不要复制粘贴 
select pinpai from car group by pinpai 和 select distinct pinpai from car
不是我要的答 因为他们之中缺少数量


回复讨论(解决方案)

create temporary table car (pinpai varchar(10));insert into car values ('Lambo'),('Audi'),('BMW'),('Audi'),('Toyota'),('Lambo');select pinpai, count(*) as cnt from car group by 1
pinpai cnt Audi   2 BMW    1 Lambo  2 Toyota 1 

你没有理解我的意思,你这不是我要的结果,我是要显示 前台显示的是:"现共有4种品牌车辆,共计6辆。" 而不是 把它们每个品牌有多少个显示出来

create temporary table car (pinpai varchar(10));insert into car values ('Lambo'),('Audi'),('BMW'),('Audi'),('Toyota'),('Lambo');select pinpai, count(*) as cnt from car group by 1
pinpai cnt Audi   2 BMW    1 Lambo  2 Toyota 1 

你没有理解我的意思,你这不是我要的结果,我是要显示 前台显示的是:"现共有4种品牌车辆,共计6辆。" 而不是 把它们每个品牌有多少个显示出来

使用group by + count(*)就可以了.

select pinpai, count(*) as num from car group by pinpai;

select count(*) pinpai, sum(cnt) as cnt  from (select pinpai, count(*) as cnt from car group by 1) T
pinpai cnt 4      6 

你是一点数据库知识都不学?

select count(*) pinpai, sum(cnt) as cnt  from (select pinpai, count(*) as cnt from car group by 1) T
pinpai cnt 4      6 

你是一点数据库知识都不学?

 
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn