1. 程式人生 > >mysql之資料去重並記錄總數

mysql之資料去重並記錄總數

引用:

http://blog.sina.com.cn/s/blog_6c9d65a10101bkgk.html
http://www.jb51.net/article/39302.htm

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、記錄兩張表的數目的和,這兩個表分開查詢

SELECT SUM(c)
FROM
  (SELECT COUNT(DISTINCT from_user_id, message_id) c
  FROM im_message
  WHERE dr = 0  AND message_status = 2  AND user_type = 1  AND to_user_id = 2
  UNION ALL
  SELECT COUNT(DISTINCT group_id, message_id) c
  FROM im_messagerefgroup
  WHERE dr = 0  AND user_id = 2
  )
AS temp ;