mysql更新自我表如何工作

how mysql update self table work(mysql更新自我表如何工作)
本文介绍了mysql更新自我表如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MYSQL 中有一个表:

I have a table in 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 |
+------+------+

我想将 b 列更新为 a 列的 min(b) 组.

I want to update column b to the min(b) group by column a.

所以 SQL 应该是:

So the SQL should be:

UPDATE test.tem o
SET o.b = (SELECT
             MIN(b)
           FROM test.tem i
           WHERE i.a = o.a)

但是 MYSQL 无法在 FROM 子句中指定要更新的目标表

所以我认为下面的 SQL 可以很好地解决我的问题:

So I think below SQL can solve my question with good performance:

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应该是什么?

Question 1: Why MYSQL work out the incorrect result with the SQL? What the correct SQL with good efficient should be?
Question 2: What the SQL should be if I only want to update b with NULL value(only update the third record)?

关于问题2,我尝试使用了下面不正确的SQL:

About question 2, I have tried to use the incorrect SQL below:

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 可能会像你想的那样更新更多的行.

You don't have an unique column to identifies your rows. So yourJOIN will probably update more rows as you think.

你可能想要这样的东西:

You probably want something like that instead:

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

如果您只想更新列 b 中具有 NULL 的行,这只是 WHERE 子句的问题:

If you only want to update the rows having NULL in column b, this is only a matter of WHERE clause:

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

这篇关于mysql更新自我表如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)