Home > php教程 > php手册 > 使用GROUP BY的时候如何统计记录条数 COUNT(*) DISTINCT

使用GROUP BY的时候如何统计记录条数 COUNT(*) DISTINCT

WBOY
Release: 2016-06-13 12:10:10
Original
1006 people have browsed it

例如这样一个表,我想统计email和passwords都不相同的记录的条数

复制代码 代码如下:


CREATE TABLE IF NOT EXISTS `test_users` (
`email_id` int(11) unsigned NOT NULL auto_increment,
`email` char(100) NOT NULL,
`passwords` char(64) NOT NULL,
PRIMARY KEY (`email_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;


INSERT INTO `test_users` (`email_id`, `email`, `passwords`) VALUES
(1, ‘jims@gmail.com', ‘1e48c4420b7073bc11916c6c1de226bb'),
(2, ‘jims@yahoo.com.cn', ‘5294cef9f1bf1858ce9d7fdb62240546′),
(3, ‘default@gmail.com', ‘5294cef9f1bf1858ce9d7fdb62240546′),
(4, ‘jims@gmail.com', ”),
(5, ‘jims@gmail.com', ”);

通常我们的做法是这样

复制代码 代码如下:


SELECT COUNT(*) FROM test_users WHERE 1 = 1 GROUP BY email,passwords


这样的结果是什么呢?

复制代码 代码如下:


COUNT(*)
1
2
1
1


显然这不是我要的结果,这样统计出来的是相同email和passwords的各个记录数量之和,下面这样就可以了

复制代码 代码如下:


SELECT COUNT(DISTINCT email,passwords) FROM `test_users` WHERE 1 = 1


当然在php里面也可以用mysql_num_rows来获取记录的条数,但是这样的效率不高,可以参考这篇文章
mysql_num_rows VS COUNT 效率问题分析
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template