SQL错误 [22P02]: 错误: 表tableName.date_unit的枚举值无效: “”

huangapple go评论105阅读模式
英文:

SQL Error [22P02]: ERROR: invalid input value for enum tableName.date_unit: ""

问题

当我尝试获取表中所有行的列表时,出现了这个错误。这只发生在我在SELECT语句中包含其中一列时。该列本身是一个枚举列,我想在遇到空值时使用COALESCE函数处理该列。

以下是我代码的简化版本:

SELECT id,
	user_id,
	coalesce(date_unit, '') date_unit
FROM table_name
WHERE user_id = $1

当我尝试运行它时,出现了以下错误:

SQL Error [22P02]: ERROR: invalid input value for enum table_name.date_unit: ""

在使用SQLX和Golang运行时,出现了以下错误:

Pq: invalid input value for enum table_name.date_unit: ""

date_unit本身是一个枚举类型,它有限定的值。在表中,它只接受daymonth作为值。但是很多行的date_unit列都有null值。

如果date_unit的值为null,我想将其转换为空字符串""

COALESCE函数在处理枚举值时是否有问题?我应该如何使用COALESCE来实现我想要的功能?

英文:

I got this error when I try to get the list of all rows on my table. This only happens because I include one of the column in the SELECT. The column itself is an enum column and I wanna use COALESCE for the column in case it meets a null value.

This is a simplication of my code

SELECT id,
	user_id,
	coalesce(date_unit, '') date_unit
FROM table_name
WHERE user_id = $1

I got this error when I try to run it

SQL Error [22P02]: ERROR: invalid input value for enum table_name.date_unit: ""

This is the error when I run it using SQLX On Golang

Pq: invalid input value for enum table_name.date_unit: \"\"

date_unit itself is an enum which has restricted values. It only accepts day and month as value in the table. But lots of rows have null value in date_unit.

I wanna convert it to "" or empty string if date_unit value is null.

Is there a problem with the COALESCE with enum values? How should I use COALESCE to work with what I wanna do?

答案1

得分: 1

答案可以在问题的评论部分找到。

为了正式化它,由于date_unit不是string类型,所以在查询时无法返回它(无效的数据类型)。因此,在查询时,我们应该将date_unit转换为字符串类型。

可以使用以下查询来完成:

SELECT id,
    user_id,
    COALESCE(date_unit::text, '')
FROM table_name
WHERE user_id = $1
英文:

The answer is found in the comment section of the question.

To officiate it, as date_unit is not a string type, it cannot be returned when querying (invalid data type). As such, when querying, we should convert date_unit to string type.

This can be done using the query:

SELECT id,
    user_id,
    COALESCE(date_unit::text, '')
FROM table_name
WHERE user_id = $1

答案2

得分: 0

选择 id,
    用户 id,
    如果 date_unit 为空则返回空字符串
从表名中
其中用户 id = $1
英文:
SELECT id,
    user_id,
    coalesce(date_unit, '')
FROM table_name
WHERE user_id = $1

huangapple
  • 本文由 发表于 2022年8月19日 17:21:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73414557.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定