我在MYSQL中有一张表:
CREATE TABLE test.tem(a INT,b INT);
具有以下数据:
INSERT INTO test.tem VALUES(1,2),(1,1),(1,NULL),(2,3);
现在数据应该是:
+------+------+ | a | b | +------+------+ | 1 | 2 | | 1 | 1 | | 1 | NULL | | 2 | 3 | +------+------+
我想按列a将b列更新为min(b)组。
因此,SQL应该是:
UPDATE test.tem o SET o.b = (SELECT MIN(b) FROM test.tem i WHERE i.a = o.a)
但是MYSQL 无法在FROM子句中指定要更新的目标表
因此,我认为下面的SQL可以很好地解决我的问题:
UPDATE test.tem t1 JOIN test.tem t2 ON t1.a = t2.a SET t1.b = t2.b WHERE t1.b IS NULL OR t1.b > t2.b;
但是结果是:
+------+------+ | a | b | +------+------+ | 1 | 1 | | 1 | 1 | | 1 | 2 | | 2 | 3 | +------+------+
实际上,我需要的结果是:
+------+------+ | a | b | +------+------+ | 1 | 1 | | 1 | 1 | | 1 | 1 | | 2 | 3 | +------+------+
问题1:为什么MYSQL用SQL计算出不正确的结果?高效的正确SQL应该是什么? 问题2:如果我只想用NULL值更新b(只更新第三条记录),那么SQL应该是什么?
关于问题2,我尝试使用以下错误的SQL:
UPDATE test.tem t1 JOIN test.tem t2 ON t1.a = t2.a AND t1.b IS NULL SET t1.b = t2.b WHERE t1.b IS NULL OR t1.b > t2.b;
您没有唯一的列来标识您的行。因此,您JOIN可能会按照自己的想法更新更多行。
JOIN
您可能想要这样的东西:
UPDATE tem AS t1 JOIN (SELECT a, MIN(b) AS m FROM tem GROUP BY a) AS t2 USING (a) SET t1.b = t2.m;
参见http://sqlfiddle.com/#!2/c6a04/1
如果您只想更新 bNULL列中的行,那么这只是子句的问题: __WHERE
NULL
WHERE
CREATE TABLE tem(a INT,b INT); INSERT INTO tem VALUES(1,2),(1,1),(1,NULL),(2,3); UPDATE tem AS t1 JOIN (SELECT a, MIN(b) AS m FROM tem GROUP BY a) AS t2 USING (a) SET t1.b = t2.m WHERE t1.b IS NULL;
参见http://sqlfiddle.com/#!2/31ffb/1