[英]Postgresql: auto lowercase text while (or before) inserting to a column
I want to achieve case insensitive uniqueness in a varchar column. 我想在varchar列中实现不区分大小写的唯一性。 But, there is no case insensitive text data type in Postgres.
但是,Postgres中没有不区分大小写的文本数据类型。 Since original case of text is not important, it will be a good idea to convert all to lowercase/uppercase before inserting in a column with UNIQUE constraint.
由于原始文本的情况并不重要,因此在插入具有UNIQUE约束的列之前将全部转换为小写/大写是一个好主意。 Also, it will require one INDEX for quick search.
此外,它将需要一个INDEX快速搜索。
Is there any way in Postgres to manipulate data before insertion? Postgres有没有办法在插入之前操作数据?
I looked at this other question: How to automatically convert a MySQL column to lowercase . 我看了另外一个问题: 如何自动将MySQL列转换为小写 。 It suggests using triggers on insert/update to lowercase text or to use views with lowercased text.
它建议在插入/更新时使用触发器来使用小写文本或使用带有小写文本的视图。 But, none of the suggested methods ensure uniqueness.
但是,所提出的方法都没有确保唯一性。
Also, since this data will be read/written by various applications, lowercasing data in every individual application is not a good idea. 此外,由于这些数据将由各种应用程序读取/写入,因此在每个单独的应用程序中降低数据并不是一个好主意。
You don't need a case-insensitive data type (although there is one ) 您不需要不区分大小写的数据类型(尽管有一个 )
CREATE UNIQUE INDEX idx_lower_unique
ON your_table (lower(the_column));
That way you don't even have to mess around with the original data. 这样你甚至不必乱用原始数据。
ALTER TABLE your_table
ADD CONSTRAINT your_table_the_column_lowercase_ck
CHECK (the_column = lower(the_column));
From the manual : 从手册 :
The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly.
使用索引来强制执行唯一约束可以被视为不应直接访问的实现细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.