Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2793194
  • 博文数量: 471
  • 博客积分: 7081
  • 博客等级: 少将
  • 技术积分: 5369
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-04 21:55
文章分类

全部博文(471)

文章存档

2014年(90)

2013年(69)

2012年(312)

分类: Mysql/postgreSQL

2012-06-28 11:17:59

 

点击(此处)折叠或打开

  1. CREATE table ts
  2. (
  3.    id int(11) not null UNIQUE,
  4.    pcode int(11) default NULL,
  5.    cno varchar(20) default null,
  6.    count1 int(11) default null
  7. )

  8. INSERT INTO `ts` VALUES ('1', '1', ' 001', '10000');
  9. INSERT INTO `ts` VALUES ('2', '1', ' 002', '5000');
  10. INSERT INTO `ts` VALUES ('3', '1', ' 003', '20000');
  11. INSERT INTO `ts` VALUES ('4', '2', ' 001', '40000');
  12. INSERT INTO `ts` VALUES ('5', '2', ' 003', '30000');
  13. INSERT INTO `ts` VALUES ('6', '3', ' 002', '90000');
  14. INSERT INTO `ts` VALUES ('7', '3', ' 002', '90000');
  15. INSERT INTO `ts` VALUES ('8', '3', ' 002', '90000');

 查询pcode字段相同2条以上的记录:

点击(此处)折叠或打开

  1. select *
  2. from ts
  3. group by pcode
  4. having count(*)>2

查询pcode字段相同的记录

点击(此处)折叠或打开

  1. select *
  2. from ts
  3. where pcode in
  4. (select pcode
  5. from ts
  6. group by pcode
  7. having count(*)>1)


查询pcode,cno,count1三个字段均相同的记录:

点击(此处)折叠或打开

  1. select *
  2. from ts
  3. where concat(pcode,cno,count1) in
  4. (
  5.     select concat(pcode,cno,count1)
  6.     from ts
  7.     group by pcode,cno,count1
  8.     having count(1) >= 2
  9. )

删除多余的pcode字段相同的记录:

点击(此处)折叠或打开

  1. SELECT *
  2. from ts
  3. where pcode in
  4. (
  5.     select pcode
  6.     from ts
  7.     group by pcode
  8.     having count(*)>1
  9. ) and id not in #查出所有相同的记录排除第一条,将全部删除掉
  10. (    
  11.     select min(id)
  12.     from ts
  13.     group by pcode
  14.     having count(*) >= 2
  15. );

删除多余的pcode,cno,count1三个字段均相同的记录:

点击(此处)折叠或打开

  1. SELECT *
  2. from ts
  3. where concat(pcode,cno,count1) in
  4. (
  5.     select concat(pcode,cno,count1)
  6.     from ts
  7.     group by pcode,cno,count1
  8.     having count(1) >= 2
  9. ) and id not in
  10. (
  11.     select min(id)
  12.   from ts
  13.     group by pcode,cno,count1
  14.   having count(1) >= 2
  15. );

在此注意:多字段的时候该语句仅适用于字段值均不为空的情况,concat函数中的参数有一个为空便会返回空值。

1.任何情况下Select COUNT(*) FROM xxx 是最优选择;
2.尽量减少Select COUNT(*) FROM xxx Where COL = ‘xxx’ 这种查询;
3.杜绝Select COUNT(COL) FROM tablename Where COL = ‘xxx’ 的出现。(其中COL非主键)

(1)count(*)是对行数目进行计数

(2)count(column_name)是对列中不为空的行进行计数,






阅读(606) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~