如何使用Group by子句更新具有特定计数的多个行?

时间:2012-03-06 18:00:31

标签: mysql count group-by duplicates

我想用40号更新具有特定计数(count(*)= 2)的多行。请考虑以下示例:

create table test(id int not null primary key, day date not null, tst int not null  );
insert into test(id, day, tst) values(1, '2006-10-08', 0);

insert into test(id, day, tst) values(2, '2006-10-08', 0);

insert into test(id, day,tst) values(3, '2006-10-09', 0);

我使用了以下查询UPDATE test SET tst = 40 WHERE (select day from test GROUP BY day having count(*)=2);

但它永远不会奏效。任何帮助请...

感谢。

Aymen

2 个答案:

答案 0 :(得分:1)

这是一个完整的例子(使用Oracle而不是mysql,但语法应该相似,如果不相同的话):

CREATE TABLE TEST (tst int, DAY INT)

INSERT INTO TEST VALUES (2, 4);
INSERT INTO TEST VALUES (3, 4);
INSERT INTO TEST VALUES (4, 5);

UPDATE TEST
   SET tst = 40
 WHERE EXISTS (SELECT DAY FROM TEST t2 WHERE t2.day = test.day GROUP BY DAY HAVING COUNT(*) = 2)
SELECT * FROM TEST;


Result:
    TST DAY
1   40  4
2   40  4
3   4   5

答案 1 :(得分:0)

感谢上帝......最后,我们提出了工作查询:

UPDATE test1 SET tst = 40 WHERE EXISTS (SELECT day FROM (SELECT day from test1 ) 
AS tmpb WHERE test1.day = tmpb.day GROUP BY day HAVING COUNT(*) = 2)