假设有表的结构及信息为:
id col2 col3 col4
1 2 2 0
2 3 2 0
3 2 2 0
4 3 2 0
5 5 3 0
以(col2,col3)分组,并统计重复记录的个数,并将统计出的个数更新到col4中,如:
id col2 col3 col4
1 2 2 2
2 3 2 2
3 2 2 2
4 3 2 2
5 5 3 1
请教大虾该怎么写SQL语句呢?更新可以发生在原表,也可以新生成一个表(最好更新原表),谢谢回复!
id col2 col3 col4
1 2 2 0
2 3 2 0
3 2 2 0
4 3 2 0
5 5 3 0
以(col2,col3)分组,并统计重复记录的个数,并将统计出的个数更新到col4中,如:
id col2 col3 col4
1 2 2 2
2 3 2 2
3 2 2 2
4 3 2 2
5 5 3 1
请教大虾该怎么写SQL语句呢?更新可以发生在原表,也可以新生成一个表(最好更新原表),谢谢回复!
示例表以及数据:
create table lk3 (
id int not null auto_increment primary key,
col2 int default 0,
col3 int default 0,
col4 int default 0
)engine=myisam charset=latin1;insert into lk3(col2,col3,col4) values
(2,2,0),
(3,2,0),
(2,2,0),
(3,2,0),
(5,3,0);
查询:
create temporary table tmp
select * from
(
select id,col2,col3,count(1) col4 from (select * from lk3 order by id asc) T group by col2,col3
union
select id,col2,col3,count(1) col4 from (select * from lk3 order by id desc) T group by col2,col3
) T order by id asc;truncate table lk3;insert into lk3 select * from tmp;drop table tmp;
结果:
query result(5 records)
id col2 col3 col4
1 2 2 2
2 3 2 2
3 2 2 2
4 3 2 2
5 5 3 1
试了一下你给出的语句,就5条记录的时候还结果准确,但如果增加到10条,15条,就不满足我的要求了,例如在15条记录的情况下:
原表为:
id col2 col3 col4
1 2 2 2
2 3 2 2
3 2 2 2
4 3 2 2
5 5 3 1
6 2 2 2
7 3 2 2
8 2 2 2
9 3 2 2
10 5 3 1
11 2 2 2
12 3 2 2
13 2 2 2
14 3 2 2
15 5 3 1
执行上述语句后,结果变为:
id col2 col3 col4
1 2 2 6
2 3 2 6
5 5 3 3
13 2 2 6
14 3 2 6
15 5 3 3
这不符合我的要求哦,我是要更新所有记录的第4列.