1、使用distinct去重(适合查询整张表的总数)
有多个学校+教师投稿,需要统计出作者的总数
select count(author) as total from files
每个作者都投稿很多,这里有重复的记录。
select distinct author from files
有可能两个学校的教师姓名相同,结果只统计一个,出错。
select distinct author,sid from files
统计(作者+学校id)的组合唯一值,结果出现正确的结果,但如何知道一共有多少人呢?
select count(distinct author,sid) as total from files
2、group by 分组去重(适合根据条件分组后查询每组的总数)
select author, count(distinct id) from files group by sid
3、记录两张表的数目的和,这两个表分开查询
1 SELECT SUM(c) 2 FROM 3 (SELECT COUNT(DISTINCT from_user_id, message_id) c 4 FROM im_message 5 WHERE dr = 0 AND message_status = 2 6 AND user_type = 1 AND to_user_id = 2 7 8 UNION ALL 9 10 SELECT COUNT(DISTINCT group_id, message_id) c 11 FROM im_messagerefgroup 12 WHERE dr = 0 AND user_id = 2) 13 AS temp;