gpt4 book ai didi

MySQL - 如何优化这个查询?

转载 作者:可可西里 更新时间:2023-11-01 07:08:33 25 4
gpt4 key购买 nike

以下查询有效,但对于 10 条记录(2 秒)来说非常慢。分析表明它正在创建一个 tmp 表,但我不确定为什么。

基本上,我将当前用户加入 acl 组,获取他们所在的所有组,然后将组加入公司,获取他们所在的所有公司,然后将公司加入订单,获得所有订单..

如果我删除这一行

ORDER BY orders.created_on DESC 

然后查询在 0.06 秒内执行(可接受)..

帮助,关于如何优化的任何想法?非常感谢:)

SELECT
orders.uuid,
companies.name as company_name
FROM
users u
JOIN
users_acl_groups g on u.uuid = g.user_uuid
JOIN
users_acl acl on (acl.user_uuid = u.uuid or acl.group_uuid = g.group_uuid)
JOIN
companies on acl.item_uuid = companies.uuid
JOIN
orders on companies.uuid = orders.company_uuid
WHERE
u.uuid = 'DDEC8073-5056-C000-01ED583A51CBCA32' and orders.status <> ''
ORDER BY orders.created_on DESC

limit 0, 10;

更新,查询的解释..

1 SIMPLE orders ALL 9403 Usingtemporary; Using filesort

1 SIMPLE acl ALL 1859 Using where;Using join buffer

1 SIMPLE g ALL 2005 Using where;Using join buffer

1 SIMPLE companies eq_ref PRIMARY PRIMARY 52 table.orders.company_uuid 1

1 SIMPLE u ALL 33595 Using where;Distinct; Using join buffer

最佳答案

您是否考虑过制作一个事实表样式的设计,作为反规范化步骤?

基本上是一种多对多的交集表,例如:

CREATE TABLE user_order_fact (
user_uuid ...
order_uuid ...
order_created_on ...
order_status ...
company_name ...,
primary key (user_uuid, order_uuid),
key (user_uuid, order_status, order_created_on, order_uuid, company_name)
);

... fill with data ...

SELECT
order_uuid,
company_name
FROM
user_order_fact
WHERE
user_uuid = 'DDEC8073-5056-C000-01ED583A51CBCA32' and order_status <> ''
ORDER BY order_created_on DESC

limit 0, 10;

我在猜测复合索引。你必须不断尝试,直到你做对为止。基本上,您是在尝试让优化器计划报告它正在使用索引

当然,这是以非规范化形式冗余存储数据,因此您需要设置一些触发器以使其与规范化表保持同步。

关于MySQL - 如何优化这个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3130171/

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