如何使用Group by子句更新具有特定计数的多个行?
问题描述:
我想更新具有特定计数次数(COUNT(*)= 2),与数40请看下面的例子多行:如何使用Group by子句更新具有特定计数的多个行?
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
答
感谢上帝......最后,我们提出了工作查询:
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)
答
这里有一个完整的示例(使用了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
谢谢dcp,它不适合我!我正在使用Mysql 5.1.33。 UPDATE语句以“HAVING COUNT(*)= 2”结尾;“我认为“select * from test”的第二句只是为了显示结果。不是吗?任何方式,我已经使用上面的句子,并与SELECT子句分离,但从来没有工作。在分离情况下,我收到了这条消息:“你无法在FROM子句中指定目标表'test1'进行更新”。 – Aymen 2012-03-07 02:55:07
我用test1表代替测试。 – Aymen 2012-03-07 03:37:44
我想出了这个查询,这也是行不通的!但我认为它更接近正确的一个。不是吗?! (SELECT * day(FROM test1 t2 from SELECT date)AS tmpb WHERE test1.day = t2.day GROUP BY day HAVING COUNT(*)= 2);这里的错误是'where子句'中的未知列't2.day'“ – Aymen 2012-03-07 07:49:59