MySQL截断命令-unicode字符

发布于 2024-08-20 07:06:02 字数 250 浏览 8 评论 0原文

我目前正在尝试调整 MySQL 中表中存储的值。存储的值包含一系列 Unicode 字符。我需要截断到 40 个字节的存储空间,但是当我尝试时:

UPDATE `MYTABLE` SET `MYCOLUMN` = LEFT(`MYCOLUMN`, 40);

MySQL 太有用了,保留了 40 个字符,而不是 40 个字节。有办法解决这个问题吗?

问候并表示感谢,

gaioshin

I am currently trying to adjust the values stored in a table in MySQL. The values stored contain a series of Unicode characters. I need to truncate to 40 bytes worth of storage, but when I try:

UPDATE `MYTABLE` SET `MYCOLUMN` = LEFT(`MYCOLUMN`, 40);

MySQL is overly helpful and retains 40 characters, rather than 40 bytes. Is there a way to get around this?

Regards and with thanks,

gaioshin

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

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

发布评论

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

评论(2

去了角落 2024-08-27 07:06:02

我不太确定您是否真的想截断为正好 40 个字节。

因为你可能会弄乱 unicode 字符,所以条件应该是
“最多 40 个字节,最后一个字符仍然有效”。

我会为此编写一个存储函数。我不确定它是否有效,但我想,你明白我的意思了:

DELIMITER &&&
CREATE FUNCTION MYTRUNCATE (subject VARCHAR(255) CHARACTER SET utf8, max_bytes INT UNSIGNED)
RETURNS VARCHAR(255) CHARACTER SET utf8
DETERMINISTIC
BEGIN
DECLARE byte_len INT;
DECLARE char_len INT;
DECLARE res VARCHAR(255) CHARACTER SET utf8;
SET res = LEFT(subject, max_bytes);
SET byte_len = BIT_LENGTH(res)/8;
SET char_len = CHAR_LENGTH(res);
WHILE byte_len > max_bytes DO
SET char_len = char_len - 1;
SET res = LEFT(res, char_len);
SET byte_len = BIT_LENGTH(res)/8;
END WHILE;
RETURN res;
END&&&
DELIMITER ;

I'm not quite sure if you really want to truncate to exactly 40 bytes.

Since you can get messed up unicode characters the condition should be
"MAX 40 bytes WITH the last character still being valid".

I'd write a stored function for that. I'm not sure it works, but I guess, you catch my drift:

DELIMITER &&&
CREATE FUNCTION MYTRUNCATE (subject VARCHAR(255) CHARACTER SET utf8, max_bytes INT UNSIGNED)
RETURNS VARCHAR(255) CHARACTER SET utf8
DETERMINISTIC
BEGIN
DECLARE byte_len INT;
DECLARE char_len INT;
DECLARE res VARCHAR(255) CHARACTER SET utf8;
SET res = LEFT(subject, max_bytes);
SET byte_len = BIT_LENGTH(res)/8;
SET char_len = CHAR_LENGTH(res);
WHILE byte_len > max_bytes DO
SET char_len = char_len - 1;
SET res = LEFT(res, char_len);
SET byte_len = BIT_LENGTH(res)/8;
END WHILE;
RETURN res;
END&&&
DELIMITER ;
橘亓 2024-08-27 07:06:02

LEFT 是字节安全的。

如何修改列数据类型,使其只能容纳 40 个字节。 MySQL 会自动为您进行截断。

ALTER TABLE table_name
  MODIFY column_name column_type_40_bytes;

LEFT is byte safe.

How about modifying the column datatype so that it can only hold 40 bytes. MySQL will automatically do the truncating for you.

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