gpt4 book ai didi

MySQL Slow LEFT JOIN Query 使用派生查询进行连接时

转载 作者:行者123 更新时间:2023-11-29 04:02:08 24 4
gpt4 key购买 nike

以下查询对两个表进行操作:dev_Profiledev_User

SELECT
dev_Profile.ID AS pid,
Name AS username,
st1.online
FROM
dev_Profile
LEFT JOIN (
SELECT
dev_User.ID,
lastActivityTime /* DATETIME */
FROM
dev_User)
AS st1 ON st1.ID = dev_Profile.UserID;

每个表中大约有 11K 行,此查询需要将近 6 秒才能完成。我还没有太多的数据库经验。我认为为 dev_Profile.UserID 创建一个索引就可以了,因为 dev_Profile.ID 已经有一个索引(它是 PK)和 dev_Profile.UserID 没有索引,但这根本没有帮助。

编辑:此查询的 EXPLAIN 输出:

+----+-------------+-------------+------+---------------+------+---------+------+-------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------------+------+---------------+------+---------+------+-------+-------+
| 1 | PRIMARY | dev_Profile | ALL | NULL | NULL | NULL | NULL | 11521 | |
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 11191 | |
| 2 | DERIVED | dev_User | ALL | NULL | NULL | NULL | NULL | 11440 | |
+----+-------------+-------------+------+---------------+------+---------+------+-------+-------+

有什么建议吗?

最佳答案

为什么要嵌套选择?这可能会使优化器感到困惑。尝试消除它:

SELECT
dev_Profile.ID AS pid,
Name AS username,
st1.online
FROM
dev_Profile
LEFT JOIN dev_User st1 ON st1.ID = dev_Profile.UserID;

关于MySQL Slow LEFT JOIN Query 使用派生查询进行连接时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12015091/

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