SQL独特的varchar大小写敏感问题

发布于 2024-11-16 18:31:21 字数 413 浏览 6 评论 0原文

我正在尝试用单词列表填充 SQL 表。表本身非常简单:

CREATE TABLE WORDS(
  ID BIGINT AUTO_INCREMENT, 
  WORD VARCHAR(128) NOT NULL UNIQUE, 
  PRIMARY KEY(ID)
);

我遇到的问题是这样的:当我连续执行以下插入时,

INSERT INTO WORDS(WORD) VALUES('Seth');
INSERT INTO WORDS(WORD) VALUES('seth');

第二次插入因违反约束而失败(“键‘WORD’的重复条目‘seth’”)。

如何使 WORD 上的 UNIQUE 约束区分大小写?

I'm trying to populate a SQL table with a list of words. The table itself it pretty simple:

CREATE TABLE WORDS(
  ID BIGINT AUTO_INCREMENT, 
  WORD VARCHAR(128) NOT NULL UNIQUE, 
  PRIMARY KEY(ID)
);

The problem I'm running into is this: when I do the following inserts back to back

INSERT INTO WORDS(WORD) VALUES('Seth');
INSERT INTO WORDS(WORD) VALUES('seth');

The second insert fails with a constraint violation ("Duplicate entry 'seth' for key 'WORD'").

How can I get the UNIQUE constraint on WORD to be case sensitive?

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

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

发布评论

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

评论(4

殊姿 2024-11-23 18:31:21

看起来 mysql 默认情况下不区分大小写

您可能需要创建具有区分大小写排序规则的列(例如 utf8_bin):

CREATE TABLE WORDS (
    ID BIGINT AUTO_INCREMENT, 
    WORD VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL UNIQUE, 
    PRIMARY KEY(ID)
);

Looks like mysql is case insensitive by default:

You probably need to create the column with a case sensitive collation (e.g. utf8_bin):

CREATE TABLE WORDS (
    ID BIGINT AUTO_INCREMENT, 
    WORD VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL UNIQUE, 
    PRIMARY KEY(ID)
);
感情洁癖 2024-11-23 18:31:21

默认情况下,MySQL 会忽略 varchar 上大小写和尾随空格的差异。

如果您需要区分大小写,可以将表更改为 varchar(...) 二进制

使用 show create table 可以更好地理解 MySQL 如何将其转换为完整表示法。

如果您需要注意尾随空格并区分大小写,请使用 varbinary 而不是 varchar

By default MySQL ignores differences in case and trailing spaces on varchar.

If you need it to be case sensitive, you can alter the table to be varchar(...) binary.

Use show create table to better understand how MySQL converts this to full notation.

If you need to pay attention to trailing spaces as well as be case sensitive, use varbinary instead of varchar.

下雨或天晴 2024-11-23 18:31:21

试试这个:

ALTER TABLE WORDS CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;

Try this:

ALTER TABLE WORDS CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin;
£噩梦荏苒 2024-11-23 18:31:21

我制作了我的唯一密钥 varchar(1000)。它起作用了。

经过一番尝试和错误后,我发现任何大于或等于 1100 varchar 的内容都会失败。

澄清一下,我没有尝试在 1001 到 1099 之间。

希望这有帮助。

I made my UNIQUE key varchar(1000). It worked.

After some trial and error, I found anything greater than or equal to 1100 varchar would fail.

To clarify I did not try between 1001 to 1099.

Hope this helps.

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