gpt4 book ai didi

php - 在第二个表 MySQL 上按顺序加入 2 个表时的索引

转载 作者:行者123 更新时间:2023-12-04 13:52:57 25 4
gpt4 key购买 nike

对于有经验的用户来说,这可能很容易,但我无法完全理解这个简单案例需要哪些索引。
我有一个前端表,除了一些可用于搜索目的的过滤器外,它可以按任何列排序:

id | username | email | name | phone | email_verified_at
显示的行是连接 2 个表(具有一对一关系)的结果:
TABLE USERS

id | autoincrement
name | string
username | string | unique
email | string | unique
email_verified_at | timestamp | nullable

INDEXES
primary(id)
unique(name,id)
unique(username)
unique(email)
unique(email_verified_at,email)
TABLE PROFILES

id | autoincrement
user_id | FK(users)
phone | string

INDEXES
primary(id)
index(user_id)
unique(phone,user_id)
最基本的查询,按用户 id 排序看起来像
select
`users`.`id` as `id`,
`users`.`name` as `name`,
`users`.`username` as `username`,
`users`.`email` as `email`,
`users`.`email_verified_at` as `email_verified_at`,
`profiles`.`phone` as `phone`
from
`users`
left join `profiles` on `users`.`id` = `profiles`.`user_id`
order by
`id` asc
limit
11
按 id、姓名、用户名、电子邮件或 email_verified_at 排序在用户表中执行完整索引扫描,我认为这是正确的。
enter image description here
但是当我尝试通过电话订购时,麻烦(或没有)来了:
select
`users`.`id` as `id`,
`users`.`name` as `name`,
`users`.`username` as `username`,
`users`.`email` as `email`,
`users`.`email_verified_at` as `email_verified_at`,
`profiles`.`phone` as `phone`
from
`users`
left join `profiles` on `users`.`id` = `profiles`.`user_id`
order by
`phone` asc
limit
11
我看到的第一件事是它正在用户表中进行全表扫描。
为了避免这种情况,我需要为包含以下内容的用户表创建一个 UNIQUE 索引:
id, username, email, name
因此,查询对用户表执行完整索引扫描。
尽管如此,我发现与按用户表字段排序相比,查询成本太高了。
enter image description here
这可以吗?我在这里错过了什么吗?我不确定这是预期结果还是可以改进。
提前致谢

最佳答案

profiles需要一个以 user_id 开头的索引.索引中列的顺序很重要。
如需进一步讨论,请提供SHOW CREATE TABLEEXPLAIN FORMAT=JSON SELECT ...

关于php - 在第二个表 MySQL 上按顺序加入 2 个表时的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67311112/

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