简体   繁体   English

如何在MySQL中用空值替换列

[英]How to replace a column with null values in mysql

One of my columns in the table contains 'NULL' values and I would like to replace them with certain values. 我在表中的一列包含'NULL'值,我想将它们替换为某些值。

I looked at this post: Replace nulls values in sql using select statement? 我看了这篇文章: 使用select语句替换sql中的null值? and followed the answer. 然后按照答案。

My sql statement: 我的SQL语句:

Select ifnull(`option`, 'MCQ') as `option` 
from question_table 

This statement returns me the columns there are already with 'MCQ', but the 'NULL' values are not replaced yet. 该语句返回给我已经有'MCQ'的列,但是'NULL'值尚未被替换。

Need some guidance to change this. 需要一些指导来改变这一点。

If you want to change the data, you need an update : 如果要更改数据,则需要update

update question_table
    set option = 'MCQ'
    where option is null;

A select statement does not change the database. select语句不会更改数据库。

If you want to update the table use Gordon's answer , but maybe you just want to return a replacement value for NULL in the SELECT , you can use COALESCE : 如果要更新表,请使用Gordon的答案 ,但是也许您只想在SELECT返回NULL的替换值,则可以使用COALESCE

SELECT COALESCE(`option`, 'MCQ') as `option` 
FROM question_table

This selects MCQ for every option -value that is NULL . 这将为每个为NULL option值选择MCQ

Another way is using CASE : 另一种方法是使用CASE

SELECT CASE WHEN `option` IS NULL THEN 'MCQ' ELSE `option` END as `option` 
FROM question_table

'NULL' is a string, NULL is a special value that means "unknown/unavailable". 'NULL'是一个字符串, NULL是一个特殊值,表示“未知/不可用”。 They are totally different things. 他们是完全不同的东西。

MySQL function IFNULL() handles NULL values (they cannot be compared using the regular comparison operators). MySQL函数IFNULL()处理NULL值(无法使用常规比较运算符比较它们)。 You can use the regular comparison operators ( = , <> ) to work with strings, even when they are 'NULL' . 可以使用常规比较运算符( =<> )处理字符串,即使它们为'NULL'

If your query produces 'NULL' values in the result set it means the values in the database are not NULL but strings ( 'NULL' ). 如果您的查询在结果集中产生'NULL'值,则意味着数据库中的值不是NULL而是字符串( 'NULL' )。

In this case the query you need is: 在这种情况下,您需要的查询是:

SELECT IF(`option` = 'NULL', 'MCQ', `option`) AS `option` 
FROM question_table 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM