1.数据库零值和空值区别
SELECT *
FROM test_table
WHERE Name = ''
Query id: 1f86b60f-3f96-45c7-8b05-52019e053195
┌─Name─┬─Age─┐
1. │ │ 111 │
└──────┴─────┘
┌─Name─┬──Age─┐
2. │ │ 1111 │
└──────┴──────┘
2 rows in set. Elapsed: 0.003 sec.
SELECT *
FROM test_table
WHERE Name IS NULL
Query id: 0ec4df2f-e92d-47ec-a6a5-776a76d36f20
┌─Name─┬──Age─┐
1. │ ᴺᵁᴸᴸ │ ᴺᵁᴸᴸ │
└──────┴──────┘
┌─Name─┬──Age─┐
2. │ ᴺᵁᴸᴸ │ ᴺᵁᴸᴸ │
└──────┴──────┘
┌─Name─┬──Age─┐
3. │ ᴺᵁᴸᴸ │ ᴺᵁᴸᴸ │
└──────┴──────┘
┌─Name─┬─Age─┐
4. │ ᴺᵁᴸᴸ │ 1 │
└──────┴─────┘
插入空值
INSERT INTO test_table2 (Name, Age) VALUES (NULL, 30);
2.解决ent填入空值问题
在 Go 语言中使用 ent 库进行数据库操作时,确实可以为字段设置空值(NULL)。ent 库提供了 Nillable
选项,允许你区分字段的零值和空值(NULL)。当你在 schema 中将一个字段设置为 Optional()
和 Nillable()
时,该字段在数据库中可以存储 NULL 值,并且在 Go 结构体中将被表示为指针类型,以便能够区分空值和零值。
以下是如何在 ent 库中为字段设置空值的示例:
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// User schema definition.
type User struct {
ent.Schema
}
// Fields of the user.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("optional_name").Optional(),
field.String("nillable_name").Optional().Nillable(),
}
}