更新所有 NULL 字段 MySQL

发布于 2024-09-08 03:36:18 字数 165 浏览 2 评论 0原文

我想将一个表中的所有 NULL 字段更新为 0。当然

UPDATE mytable SET firstcol=0 WHERE firstcol IS NULL 

可以完成这项工作。但我想知道是否有比只为每列 c&p 这条线更聪明的解决方案。

I'd like to update all NULL fields in one table to 0. Of course

UPDATE mytable SET firstcol=0 WHERE firstcol IS NULL 

would do the job. But I wonder if there´s a smarter solution than just c&p this line for every column.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

我家小可爱 2024-09-15 03:36:18

您可以执行此操作 - 根据需要对每一列重复:

UPDATE `table1`  SET
    `col1` = IFNULL(col1, 0),
    `col2` = IFNULL(col2, 0);

示例:

DROP TABLE IF EXISTS `table1`;

CREATE TABLE `table1` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `col1` int(10) unsigned,
  `col2` int(10) unsigned,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

INSERT INTO `table1` VALUES
(1,    1, NULL),
(2, NULL, NULL),
(3,    2, NULL),
(4, NULL, NULL),
(5,    3,    4),
(6,    5,    6),
(7,    7, NULL);

UPDATE `table1`  SET
    `col1` = IFNULL(col1, 0),
    `col2` = IFNULL(col2, 0);

SELECT * FROM `table1`;

+----+------+------+
| id | col1 | col2 |
+----+------+------+
|  1 |    1 |    0 |
|  2 |    0 |    0 |
|  3 |    2 |    0 |
|  4 |    0 |    0 |
|  5 |    3 |    4 |
|  6 |    5 |    6 |
|  7 |    7 |    0 |
+----+------+------+

UPDATE

如果您想通过更改列来更改表结构,以便它们不再接受空值,您可以使用存储过程来完成。以下存储过程查询 INFORMATION_SCHEMA COLUMNS 以获取有关以下内容的信息:给定数据库表中的列。根据该信息,它构建了一个准备好的语句,然后用于更改表结构。您可能需要对其进行调整以满足您的具体要求 - 目前,它会查找未设置 NOT NULLINT 列:

delimiter //
DROP PROCEDURE IF EXISTS no_nulls//
CREATE PROCEDURE `no_nulls` (IN param_schema CHAR(255), IN param_table CHAR(255))
BEGIN

    SET @alter_cmd = (SELECT CONCAT(
        'ALTER TABLE ',
        param_table,
        GROUP_CONCAT(
            ' MODIFY COLUMN ',
            `column_name`, ' ',
            `column_type`,
            ' NOT NULL'
            SEPARATOR ', ')
        ) AS `sql_cmd`
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE `table_schema` = param_schema
    AND `table_name` = param_table
    AND LCASE(`data_type`) = 'int'
    AND LCASE(`is_nullable`) = 'yes');

    IF NOT ISNULL(@alter_cmd) THEN
        SELECT @alter_cmd;
        PREPARE stmt FROM @alter_cmd;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;

END//
delimiter ;

示例:

CREATE TABLE `test`.`table1` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `col1` int(10) unsigned,
  `col2` int(10) unsigned,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

CALL no_nulls('test', 'table1');
    +----------------------------------------------------------------------------------------------------------------+
| @alter_cmd                                                                                                     |
+----------------------------------------------------------------------------------------------------------------+
| ALTER TABLE table1 MODIFY COLUMN col1 int(10) unsigned NOT NULL,  MODIFY COLUMN col2 int(10) unsigned NOT NULL |
+----------------------------------------------------------------------------------------------------------------+

SHOW CREATE TABLE `test`.`table1`;

CREATE TABLE `table1` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `col1` int(10) unsigned NOT NULL,
    `col2` int(10) unsigned NOT NULL,
    PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

以下行显示要执行的命令,如有必要,可以从存储过程中删除:

SELECT @alter_cmd;

You could do this - repeat as necessary for each column:

UPDATE `table1`  SET
    `col1` = IFNULL(col1, 0),
    `col2` = IFNULL(col2, 0);

Example:

DROP TABLE IF EXISTS `table1`;

CREATE TABLE `table1` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `col1` int(10) unsigned,
  `col2` int(10) unsigned,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

INSERT INTO `table1` VALUES
(1,    1, NULL),
(2, NULL, NULL),
(3,    2, NULL),
(4, NULL, NULL),
(5,    3,    4),
(6,    5,    6),
(7,    7, NULL);

UPDATE `table1`  SET
    `col1` = IFNULL(col1, 0),
    `col2` = IFNULL(col2, 0);

SELECT * FROM `table1`;

+----+------+------+
| id | col1 | col2 |
+----+------+------+
|  1 |    1 |    0 |
|  2 |    0 |    0 |
|  3 |    2 |    0 |
|  4 |    0 |    0 |
|  5 |    3 |    4 |
|  6 |    5 |    6 |
|  7 |    7 |    0 |
+----+------+------+

UPDATE

If you want to alter the table structure by changing columns so that they no longer accept nulls, you could do it with a stored procedure. The following stored procedure queries the INFORMATION_SCHEMA COLUMNS for information about columns in a given database table. From that information, it builds up a prepared statement which is then used to alter the table structure. You may need to tweak it to suit your exact requirements - at the moment, it looks for INT columns which do not have NOT NULL set:

delimiter //
DROP PROCEDURE IF EXISTS no_nulls//
CREATE PROCEDURE `no_nulls` (IN param_schema CHAR(255), IN param_table CHAR(255))
BEGIN

    SET @alter_cmd = (SELECT CONCAT(
        'ALTER TABLE ',
        param_table,
        GROUP_CONCAT(
            ' MODIFY COLUMN ',
            `column_name`, ' ',
            `column_type`,
            ' NOT NULL'
            SEPARATOR ', ')
        ) AS `sql_cmd`
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE `table_schema` = param_schema
    AND `table_name` = param_table
    AND LCASE(`data_type`) = 'int'
    AND LCASE(`is_nullable`) = 'yes');

    IF NOT ISNULL(@alter_cmd) THEN
        SELECT @alter_cmd;
        PREPARE stmt FROM @alter_cmd;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;

END//
delimiter ;

Example:

CREATE TABLE `test`.`table1` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `col1` int(10) unsigned,
  `col2` int(10) unsigned,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

CALL no_nulls('test', 'table1');
    +----------------------------------------------------------------------------------------------------------------+
| @alter_cmd                                                                                                     |
+----------------------------------------------------------------------------------------------------------------+
| ALTER TABLE table1 MODIFY COLUMN col1 int(10) unsigned NOT NULL,  MODIFY COLUMN col2 int(10) unsigned NOT NULL |
+----------------------------------------------------------------------------------------------------------------+

SHOW CREATE TABLE `test`.`table1`;

CREATE TABLE `table1` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `col1` int(10) unsigned NOT NULL,
    `col2` int(10) unsigned NOT NULL,
    PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The following line displays the command that is to be executed, and may be removed from the stored procedure if necessary:

SELECT @alter_cmd;
成熟的代价 2024-09-15 03:36:18

您可以将列ALTER更改为NOT NULL DEFAULT 0吗?

您可以按照 MySQL 文档:

您可以在单个 ALTER TABLE 语句中发出多个 ADD、ALTER、DROP 和 CHANGE 子句,并用逗号分隔。这是标准 SQL 的 MySQL 扩展,每个 ALTER TABLE 语句仅允许每个子句之一。

Can you just ALTER the columns to NOT NULL DEFAULT 0?

You can do this in a single statement, as per MySQL documentation:

You can issue multiple ADD, ALTER, DROP, and CHANGE clauses in a single ALTER TABLE statement, separated by commas. This is a MySQL extension to standard SQL, which allows only one of each clause per ALTER TABLE statement.

幸福不弃 2024-09-15 03:36:18

您可能希望将列更改为NOT NULL

ALTER TABLE your_table MODIFY COLUMN your_field INT NOT NULL;

测试用例:

CREATE TABLE nulltable (id INT);

INSERT INTO nulltable VALUES (1);
INSERT INTO nulltable VALUES (2);
INSERT INTO nulltable VALUES (3);
INSERT INTO nulltable VALUES (NULL);
INSERT INTO nulltable VALUES (NULL);
INSERT INTO nulltable VALUES (NULL);
INSERT INTO nulltable VALUES (5);

结果:

mysql> SELECT * FROM nulltable;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
| NULL |
| NULL |
| NULL |
|    5 |
+------+
7 rows in set (0.00 sec)

mysql> ALTER TABLE nulltable MODIFY COLUMN id INT NOT NULL;
Query OK, 7 rows affected, 3 warnings (0.08 sec)
Records: 7  Duplicates: 0  Warnings: 3

mysql> SELECT * FROM nulltable;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  0 |
|  0 |
|  0 |
|  5 |
+----+
7 rows in set (0.00 sec)

You may want to alter your columns to NOT NULL.

ALTER TABLE your_table MODIFY COLUMN your_field INT NOT NULL;

Test case:

CREATE TABLE nulltable (id INT);

INSERT INTO nulltable VALUES (1);
INSERT INTO nulltable VALUES (2);
INSERT INTO nulltable VALUES (3);
INSERT INTO nulltable VALUES (NULL);
INSERT INTO nulltable VALUES (NULL);
INSERT INTO nulltable VALUES (NULL);
INSERT INTO nulltable VALUES (5);

Result:

mysql> SELECT * FROM nulltable;
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
| NULL |
| NULL |
| NULL |
|    5 |
+------+
7 rows in set (0.00 sec)

mysql> ALTER TABLE nulltable MODIFY COLUMN id INT NOT NULL;
Query OK, 7 rows affected, 3 warnings (0.08 sec)
Records: 7  Duplicates: 0  Warnings: 3

mysql> SELECT * FROM nulltable;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  0 |
|  0 |
|  0 |
|  5 |
+----+
7 rows in set (0.00 sec)
再浓的妆也掩不了殇 2024-09-15 03:36:18

并非没有中间技术或光标。您可以使用 DESCRIBE mytable; 获取列名称并循环它们以构建您的 UPDATE 查询。

所以这是可能的。但当你写下这些内容时,你可能已经复制并粘贴了;)

Not without an intermediate technology or cursor. You could use DESCRIBE mytable; to get the column names and loop over them to build your UPDATE queries.

So it is possible. But by the time it took you to write that, you probably just could have copy and pasted ;)

望笑 2024-09-15 03:36:18

这对我有用!

UPDATE `results`  SET
    column1  = IFNULL(column1,0),
    column2  = IFNULL(column2,'');

这是迈克的答案,但没有左侧列的引号!

注意:如果列的数据类型为int,则如果您尝试将值设置为“0”而不是空字符串

This worked for me!

UPDATE `results`  SET
    column1  = IFNULL(column1,0),
    column2  = IFNULL(column2,'');

This is mike's answer but without the quotes for columns on the left !

Note: If you are trying to set your values '0' instead of an empty string if a column's datatype is int

与往事干杯 2024-09-15 03:36:18

我不相信有;任何对不满足 where 子句的行起作用的语句都会更新您不打算更新的行。杰森的答案是正确的,但是,我认为有点不安全,除非你真的确定这就是你想要的。

I don't believe there is; any statement that worked on rows that didn't satisfy the where clause would update rows you didn't intent to update. Jason's answer is correct, but, I think, a bit unsafe, unless you are really sure that's what you want.

坏尐絯 2024-09-15 03:36:18

ALTER TABLE dataBaseName.tableName
ADD COLUMN columnX INT(20) NULL DEFAULT 1 AFTER columnY;

它执行以下操作

  1. 在columnY之后添加一个新列columnX。
  2. 将整个列 columnX 的值设置为默认值 1

           columnY             columnX 

         | cellValueA     |     1       |        
         | cellValueB     |     1       |
         | cellValueC     |     1       |
         | cellValueD     |     1       |

ALTER TABLE dataBaseName.tableName
ADD COLUMN columnX INT(20) NULL DEFAULT 1 AFTER columnY;

It does the following

  1. adds a new column columnX after columnY.
  2. sets its value to default 1 throughout the column columnX

           columnY             columnX 

         | cellValueA     |     1       |        
         | cellValueB     |     1       |
         | cellValueC     |     1       |
         | cellValueD     |     1       |
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文