gpt4 book ai didi

MySQL GROUP_CONCAT 转义

转载 作者:IT老高 更新时间:2023-10-29 00:08:42 25 4
gpt4 key购买 nike

(注意:这个问题不是关于转义查询,而是关于转义结果)

我正在使用 GROUP_CONCAT将多行组合成一个逗号分隔的列表。例如,假设我有两个(示例)表:

CREATE TABLE IF NOT EXISTS `Comment` (
`id` int(11) unsigned NOT NULL auto_increment,
`post_id` int(11) unsigned NOT NULL,
`name` varchar(255) collate utf8_unicode_ci NOT NULL,
`comment` varchar(255) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `post_id` (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ;

INSERT INTO `Comment` (`id`, `post_id`, `name`, `comment`) VALUES
(1, 1, 'bill', 'some comment'),
(2, 1, 'john', 'another comment'),
(3, 2, 'bill', 'blah'),
(4, 3, 'john', 'asdf'),
(5, 4, 'x', 'asdf');


CREATE TABLE IF NOT EXISTS `Post` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;

INSERT INTO `Post` (`id`, `title`) VALUES
(1, 'first post'),
(2, 'second post'),
(3, 'third post'),
(4, 'fourth post'),
(5, 'fifth post'),
(6, 'sixth post');

我想列出所有帖子以及对帖子发表评论的每个用户名的列表:

SELECT
Post.id as post_id, Post.title as title, GROUP_CONCAT(name)
FROM Post
LEFT JOIN Comment on Comment.post_id = Post.id
GROUP BY Post.id

给我:

id  title   GROUP_CONCAT( name )
1 first post bill,john
2 second post bill
3 third post john
4 fourth post x
5 fifth post NULL
6 sixth post NULL

这很好用,但如果用户名包含逗号,则会破坏用户列表。 MySQL 是否有一个函数可以让我转义这些字符? (请假设用户名可以包含任何字符,因为这只是一个示例架构)

最佳答案

实际上,有ascii控制字符专门用于分隔数据库字段和记录:

0x1F (31): unit (fields) separator

0x1E (30): record separator

0x1D (29): group separator

阅读更多:about ascii characters

您永远不会在用户名中使用它们,并且很可能永远不会在数据库中的任何其他非二进制数据中使用它们,因此可以安全地使用它们:

GROUP_CONCAT(foo SEPARATOR 0x1D)

然后用 CHAR(0x1D) 以您想要的任何客户端语言进行拆分。

关于MySQL GROUP_CONCAT 转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/452357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com