MySQL 性能:使用 GROUP_CONCAT 的单个查询,还是两个单独的查询?

发布于 2024-08-08 10:51:52 字数 578 浏览 6 评论 0原文

我有一个MySQL数据库,其中每个用户都有一个帐户,每个帐户可以有多个权限。

我的最终目标是得到帐户的用户名和以逗号分隔的权限 ID 列表。有两种方法可以实现此目的:

SELECT a.username, GROUP_CONCAT(rp.permission_id) as permission_ids
FROM account AS a
JOIN role_permission AS rp
ON rp.role_id = a.role_id
WHERE a.id = 1902

... 或 ...

SELECT username
FROM account
WHERE id = 1902;

SELECT permission_id
FROM account_permission
WHERE account_id = 1902

通过单个查询,我就可以得到完全符合我想要的结果。对于两个查询,我必须使用第二个结果集在应用程序 (PHP) 中创建逗号分隔列表。

是否有任何性能原因不选择第一个选项?我以前从未使用过 GROUP_CONCAT,所以我不知道它对性能的影响。

I have a MySQL database in which each user has an account, and each account can have multiple permissions.

My ultimate goal is to end up with the account's username, and a comma-delimited list of permissions ids. There are two ways I can accomplish this:

SELECT a.username, GROUP_CONCAT(rp.permission_id) as permission_ids
FROM account AS a
JOIN role_permission AS rp
ON rp.role_id = a.role_id
WHERE a.id = 1902

... or ...

SELECT username
FROM account
WHERE id = 1902;

SELECT permission_id
FROM account_permission
WHERE account_id = 1902

With the single query, I get my results exactly as I want them. With two queries, I have to create the comma-delimited list in the app (PHP) using the second result set.

Are there any performance reasons to NOT choose the first option? I have never used GROUP_CONCAT before, so I don't know the implications of it, performance-wise.

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

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

发布评论

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

评论(1

攒眉千度 2024-08-15 10:51:52

性能应该还不错——比两个查询要好。您需要注意 长度是虽然有限

结果被截断为 group_concat_max_len系统变量,默认值为1024。虽然返回值的有效最大长度受到max_allowed_pa​​cket值的限制,但该值可以设置得更高。在运行时更改 group_concat_max_len 值的语法如下,其中 val 是无符号整数:

SET [GLOBAL | SESSION] group_concat_max_len = val;

The performance should be OK - better than two queries. You need to be aware that the length is limited though:

The result is truncated to the maximum length that is given by the group_concat_max_len system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value of max_allowed_packet. The syntax to change the value of group_concat_max_len at runtime is as follows, where val is an unsigned integer:

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